Example usage for java.util.concurrent ConcurrentHashMap put

List of usage examples for java.util.concurrent ConcurrentHashMap put

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentHashMap put.

Prototype

public V put(K key, V value) 

Source Link

Document

Maps the specified key to the specified value in this table.

Usage

From source file:be.solidx.hot.test.TestScriptExecutors.java

@SuppressWarnings("rawtypes")
private Collection<Long> multiThreadedTest(final Script script, final int max,
        final ScriptExecutor scriptExecutor) throws InterruptedException {
    final int iterations = 100;
    ExecutorService executor = Executors.newFixedThreadPool(8);
    final ConcurrentHashMap<String, Long> results = new ConcurrentHashMap<String, Long>();
    final ConcurrentHashMap<String, Long> avgs = new ConcurrentHashMap<String, Long>();
    long benchStart = System.currentTimeMillis();
    for (int i = 0; i < iterations; i++) {
        Runnable runnable = new Runnable() {
            @SuppressWarnings("unchecked")
            @Override/* w  w  w  .ja va 2s  .co  m*/
            public void run() {
                try {
                    long res = 0;
                    Map<String, Object> parameters = new HashMap<String, Object>();
                    parameters.put("i", new Integer(max));
                    parameters.put("n", new Integer(0));

                    //long starting = System.currentTimeMillis();
                    Object object = scriptExecutor.execute(script, parameters);
                    if (object instanceof Bindings) {
                        Bindings bindings = (Bindings) object;
                        res = (Integer) bindings.get("result");
                        bindings.clear();
                    } else if (object instanceof Double) {
                        res = Math.round((Double) object);
                    } else if (object instanceof Long) {
                        res = (long) object;
                    } else
                        res = new Long((Integer) object);
                    long end = System.currentTimeMillis() - avgs.get(this.toString());
                    results.put(UUID.randomUUID().getLeastSignificantBits() + "", res);
                    avgs.put(this.toString(), end);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        avgs.put(runnable.toString(), System.currentTimeMillis());
        executor.submit(runnable);
    }

    while (results.size() < iterations) {
        Thread.sleep(50);
    }
    //Thread.sleep(20000);
    double sum = 0;
    for (Long value : avgs.values()) {
        sum += value;
    }
    System.out.println((sum / (double) iterations) + "");
    System.out.println("==== Time needed for all requests: " + (System.currentTimeMillis() - benchStart));
    results.remove("avg");
    executor = null;
    return results.values();
}

From source file:com.web.server.EARDeployer.java

/**
 * This method configures the executor services from the jar file.
 * /*from   w w w  .  j  a v a 2 s.  co  m*/
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deployExecutorServicesEar(String earFileName, FileObject earFile,
        StandardFileSystemManager fsManager) throws FileSystemException {
    try {
        System.out.println("EARFILE NAMEs=" + earFileName);
        CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>();
        ConcurrentHashMap jarClassListMap = new ConcurrentHashMap();
        CopyOnWriteArrayList<String> classList;
        obtainUrls(earFile, earFile, fileObjects, jarClassListMap, warObjects, fsManager);
        VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader(
                fileObjects.toArray(new FileObject[fileObjects.size()]), fsManager,
                Thread.currentThread().getContextClassLoader());
        VFSClassLoader customClassLoader = null;
        Set keys = jarClassListMap.keySet();
        Iterator key = keys.iterator();
        FileObject jarFileObject;
        ConcurrentHashMap classLoaderPath = new ConcurrentHashMap();
        filesMap.put(earFileName, classLoaderPath);
        for (FileObject warFileObj : warObjects) {
            if (warFileObj.getName().getBaseName().endsWith(".war")) {
                //logger.info("filePath"+filePath);
                String filePath = scanDirectory + "/" + warFileObj.getName().getBaseName();
                log.info(filePath);
                String fileName = warFileObj.getName().getBaseName();
                WebClassLoader classLoader = new WebClassLoader(new URL[] {});
                log.info(classLoader);
                warDeployer.deleteDir(
                        new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))));
                new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs();
                log.info(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                urlClassLoaderMap.put(
                        deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")),
                        classLoader);
                classLoaderPath.put(warFileObj.getName().getBaseName(),
                        deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                warDeployer.extractWar(new File(filePath), classLoader);

                if (exec != null) {
                    exec.shutdown();
                }
                new File(scanDirectory + "/" + warFileObj.getName().getBaseName()).delete();
                exec = Executors.newSingleThreadScheduledExecutor();
                exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
            }
        }
        for (int keyCount = 0; keyCount < keys.size(); keyCount++) {
            jarFileObject = (FileObject) key.next();
            {
                classList = (CopyOnWriteArrayList<String>) jarClassListMap.get(jarFileObject);
                customClassLoader = new VFSClassLoader(jarFileObject, fsManager, customClassLoaderBaseLib);
                this.urlClassLoaderMap.put(
                        scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName(),
                        customClassLoader);
                classLoaderPath.put(jarFileObject.getName().getBaseName(),
                        scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName());
                for (int classCount = 0; classCount < classList.size(); classCount++) {
                    String classwithpackage = classList.get(classCount).substring(0,
                            classList.get(classCount).indexOf(".class"));
                    classwithpackage = classwithpackage.replace("/", ".");
                    // System.out.println("classList:"+classwithpackage.replace("/","."));
                    try {
                        if (!classwithpackage.contains("$")) {

                            /*System.out.println("EARFILE NAME="+fileName);
                            System.out
                                  .println(scanDirectory
                            + "/"
                            + fileName
                            + "/"
                            + jarFileObject.getName()
                                  .getBaseName());
                                    
                            System.out.println(urlClassLoaderMap);*/
                            Class executorServiceClass = customClassLoader.loadClass(classwithpackage);

                            Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations();

                            if (classServicesAnnot != null) {
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof RemoteCall) {
                                        RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount];
                                        //registry.unbind(remoteCall.servicename());
                                        System.out.println(remoteCall.servicename().trim());
                                        try {
                                            for (int count = 0; count < 2; count++) {
                                                RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject
                                                        .exportObject(
                                                                (Remote) executorServiceClass.newInstance(), 0);
                                                registry.rebind(remoteCall.servicename().trim(), reminterface);
                                            }
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                            }
                            // System.out.println(executorServiceClass.newInstance());
                            // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                            // System.out.println();
                            Method[] methods = executorServiceClass.getDeclaredMethods();
                            for (Method method : methods) {
                                Annotation[] annotations = method.getDeclaredAnnotations();
                                for (Annotation annotation : annotations) {
                                    if (annotation instanceof ExecutorServiceAnnot) {
                                        ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                                        ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo();
                                        executorServiceInfo.setExecutorServicesClass(executorServiceClass);
                                        executorServiceInfo.setMethod(method);
                                        executorServiceInfo.setMethodParams(method.getParameterTypes());
                                        //                              System.out.println("serice name="
                                        //                                    + executorServiceAnnot
                                        //                                          .servicename());
                                        //                              System.out.println("method info="
                                        //                                    + executorServiceInfo);
                                        //                              System.out.println(method);
                                        // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw
                                        // new Exception();
                                        executorServiceMap.put(executorServiceAnnot.servicename(),
                                                executorServiceInfo);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            jarFileObject.close();
        }
        for (FileObject fobject : fileObjects) {
            fobject.close();
        }
        System.out.println("Channel unlocked");
        earFile.close();
        fsManager.closeFileSystem(earFile.getFileSystem());
        // ClassLoaderUtil.closeClassLoader(customClassLoader);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.EasyWorkflowPortlet.java

/**
 * Data transmision to vizualize Portlet UI
 *///from   ww w  . ja  v  a  2 s .com
@Override
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    response.setContentType("text/html");
    if (!isInited()) {
        getPortletContext().getRequestDispatcher("/WEB-INF/jsp/error/init.jsp").include(request, response);
        return;
    }
    openRequestAttribute(request);
    // WSPgradeLogger.viewStart(request.getRemoteUser(), this.getClass().getName());
    try {
        //if("main".equals(request.getParameter("render"))) jsp=mainjsp;
        if (request.getAttribute("jsp") == null)
            request.setAttribute("jsp", mainjsp);

        if (request.getAttribute("jsp").equals(mainjsp)) {
            ConcurrentHashMap wfmainhsh = new ConcurrentHashMap();
            ConcurrentHashMap wfhsh = PortalCacheService.getInstance().getUser(request.getRemoteUser())
                    .getWorkflows();
            Enumeration keys = wfhsh.keys();
            while (keys.hasMoreElements()) {
                String wf = keys.nextElement().toString();
                WorkflowData wData = PortalCacheService.getInstance().getUser(request.getRemoteUser())
                        .getWorkflow(wf);
                if (wData.isAppMain()) {
                    //System.out.println("main found :" + wf);
                    wfmainhsh.put(wf, wfhsh.get(wf));
                }
            }

            request.setAttribute("appWorkflowList", Sorter.getInstance().sortFromValues(wfmainhsh));//wfmainhsh
        }
        request.setAttribute("userID", request.getRemoteUser());
        request.setAttribute("portalID", PropertyLoader.getInstance().getProperty("service.url"));
        PortletRequestDispatcher dispatcher = null;
        dispatcher = pContext.getRequestDispatcher((String) request.getAttribute("jsp"));
        dispatcher.include(request, response);
    } catch (IOException e) {
        throw new PortletException("JSPPortlet.doView exception", e);
    }
    cleanRequestAttribute(request.getPortletSession());
    //        action = "";
    //        WSPgradeLogger.viewStop(request.getRemoteUser(), this.getClass().getName());
}

From source file:com.gizwits.aircondition.activity.control.MainControlActivity.java

/**
 * ??//from w  ww. ja  va 2 s.c o  m
 * 
 * @param map
 *            the map
 * @param json
 *            the json
 * @throws JSONException
 *             the JSON exception
 */
private void inputDataToMaps(ConcurrentHashMap<String, Object> map, String json) throws JSONException {
    Log.i("Apptest", json);
    JSONObject receive = new JSONObject(json);
    Iterator actions = receive.keys();
    while (actions.hasNext()) {

        String action = actions.next().toString();
        Log.i("revjson", "action=" + action);
        // 
        if (action.equals("cmd") || action.equals("qos") || action.equals("seq") || action.equals("version")) {
            continue;
        }
        JSONObject params = receive.getJSONObject(action);
        Log.i("revjson", "params=" + params);
        Iterator it_params = params.keys();
        while (it_params.hasNext()) {
            String param = it_params.next().toString();
            Object value = params.get(param);
            map.put(param, value);
            Log.i(TAG, "Key:" + param + ";value" + value);
        }
    }
    handler.sendEmptyMessage(handler_key.UPDATE_UI.ordinal());
}

From source file:org.wso2.carbon.event.input.adapter.core.internal.CarbonInputEventAdapterService.java

@Override
public void create(InputEventAdapterConfiguration inputEventAdapterConfiguration,
        InputEventAdapterSubscription inputEventAdapterSubscription) throws InputEventAdapterException {
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    ConcurrentHashMap<String, InputAdapterRuntime> eventAdapters = tenantSpecificEventAdapters.get(tenantId);
    if (eventAdapters == null) {
        tenantSpecificEventAdapters.putIfAbsent(tenantId, new ConcurrentHashMap<String, InputAdapterRuntime>());
        eventAdapters = tenantSpecificEventAdapters.get(tenantId);
    }/* w w w  . j av  a  2 s.co m*/
    InputEventAdapterFactory adapterFactory = eventAdapterFactoryMap
            .get(inputEventAdapterConfiguration.getType());
    if (adapterFactory == null) {
        throw new InputEventAdapterException(
                "Input Event Adapter not created as no adapter factory is registered " + "with type "
                        + inputEventAdapterConfiguration.getType());
    }
    if (inputEventAdapterConfiguration.getName() == null) {
        throw new InputEventAdapterException("Input Event Adapter name cannot be null, for the adapter type "
                + inputEventAdapterConfiguration.getType());
    }
    if (eventAdapters.get(inputEventAdapterConfiguration.getName()) != null) {
        throw new InputEventAdapterException(
                "Input Event Adapter not created as another adapter with same name '"
                        + inputEventAdapterConfiguration.getName() + "' already exist for tenant " + tenantId);
    }
    Map<String, String> globalProperties = InputEventAdapterServiceValueHolder.getGlobalAdapterConfigs()
            .getAdapterConfig(inputEventAdapterConfiguration.getType()).getGlobalPropertiesAsMap();

    InputEventAdapter inputEventAdapter = adapterFactory.createEventAdapter(inputEventAdapterConfiguration,
            globalProperties);
    InputAdapterRuntime inputAdapterRuntime = new InputAdapterRuntime(inputEventAdapter,
            inputEventAdapterConfiguration.getName(), inputEventAdapterSubscription);

    eventAdapters.put(inputEventAdapterConfiguration.getName(), inputAdapterRuntime);
    if (startTriggered) {
        inputAdapterRuntime.start();
    }
    if (startPollingTriggered) {
        inputAdapterRuntime.startPolling();
    }
}

From source file:org.wso2.carbon.event.input.adaptor.mqtt.MQTTEventAdaptorType.java

private void createMQTTAdaptorListener(
        InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
        InputEventAdaptorListener inputEventAdaptorListener,
        InputEventAdaptorConfiguration inputEventAdaptorConfiguration, AxisConfiguration axisConfiguration,
        String subscriptionId, int tenantId) {

    String topic = inputEventAdaptorMessageConfiguration.getInputMessageProperties()
            .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC);
    Map<String, ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>>> tenantSpecificListenerMap = inputEventAdaptorListenerMap
            .get(tenantId);/*w ww.  ja v  a 2 s  .com*/
    if (tenantSpecificListenerMap == null) {
        tenantSpecificListenerMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>>>();
        inputEventAdaptorListenerMap.put(tenantId, tenantSpecificListenerMap);
    }

    ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>> adaptorSpecificListenerMap = tenantSpecificListenerMap
            .get(inputEventAdaptorConfiguration.getName());

    if (adaptorSpecificListenerMap == null) {
        adaptorSpecificListenerMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>>();
        if (null != tenantSpecificListenerMap.put(inputEventAdaptorConfiguration.getName(),
                adaptorSpecificListenerMap)) {
            adaptorSpecificListenerMap = tenantSpecificListenerMap
                    .get(inputEventAdaptorConfiguration.getName());
        }
    }

    ConcurrentHashMap<String, MQTTAdaptorListener> topicSpecificListenMap = adaptorSpecificListenerMap
            .get(topic);
    if (topicSpecificListenMap == null) {
        topicSpecificListenMap = new ConcurrentHashMap<String, MQTTAdaptorListener>();
        if (null != adaptorSpecificListenerMap.putIfAbsent(topic, topicSpecificListenMap)) {
            topicSpecificListenMap = adaptorSpecificListenerMap.get(topic);
        }
    }

    MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(
            inputEventAdaptorConfiguration.getInputProperties().get(MQTTEventAdaptorConstants.ADAPTOR_CONF_URL),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_USERNAME),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_PASSWORD),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_CLEAN_SESSION),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_KEEP_ALIVE));
    MQTTAdaptorListener mqttAdaptorListener = new MQTTAdaptorListener(mqttBrokerConnectionConfiguration,
            inputEventAdaptorMessageConfiguration.getInputMessageProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC),
            inputEventAdaptorMessageConfiguration.getInputMessageProperties().get(
                    MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_CLIENTID),
            inputEventAdaptorListener, tenantId);
    topicSpecificListenMap.put(subscriptionId, mqttAdaptorListener);
    mqttAdaptorListener.createConnection();

}

From source file:org.apache.geode.cache.client.internal.PoolImpl.java

private void authenticateOnAllServers(Op op) {
    if (this.multiuserSecureModeEnabled && ((AbstractOp) op).needsUserId()) {
        UserAttributes userAttributes = UserAttributes.userAttributes.get();
        if (userAttributes != null) {
            ConcurrentHashMap<ServerLocation, Long> map = userAttributes.getServerToId();

            if (this.queueManager == null) {
                throw new SubscriptionNotEnabledException();
            }//from   w ww  .j  av a 2  s  . co m
            Connection primary = this.queueManager.getAllConnectionsNoWait().getPrimary();
            if (primary != null && !map.containsKey(primary.getServer())) {
                Long userId = (Long) AuthenticateUserOp.executeOn(primary.getServer(), this,
                        userAttributes.getCredentials());
                if (userId != null) {
                    map.put(primary.getServer(), userId);
                }
            }

            List<Connection> backups = this.queueManager.getAllConnectionsNoWait().getBackups();
            for (int i = 0; i < backups.size(); i++) {
                Connection conn = backups.get(i);
                if (!map.containsKey(conn.getServer())) {
                    Long userId = (Long) AuthenticateUserOp.executeOn(conn.getServer(), this,
                            userAttributes.getCredentials());
                    if (userId != null) {
                        map.put(conn.getServer(), userId);
                    }
                }
            }
        } else {
            throw new UnsupportedOperationException(
                    LocalizedStrings.MultiUserSecurityEnabled_USE_POOL_API.toLocalizedString());
        }
    }
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.ComBat.java

private void runNonParametric(final DoubleMatrix2D sdata, DoubleMatrix2D gammastar, DoubleMatrix2D deltastar) {
    final ConcurrentHashMap<String, DoubleMatrix1D[]> results = new ConcurrentHashMap<>();
    int numThreads = Math.min(batches.size(), Runtime.getRuntime().availableProcessors());

    ComBat.log.info("Runing nonparametric estimation on " + numThreads + " threads");

    Future<?>[] futures = new Future[numThreads];
    ExecutorService service = Executors.newCachedThreadPool();

    /*// w  ww  .  java  2 s  .  c  o  m
     * Divvy up batches over threads.
     */

    int batchesPerThread = batches.size() / numThreads;

    final String[] batchIds = batches.keySet().toArray(new String[] {});

    for (int i = 0; i < numThreads; i++) {

        final int firstBatch = i * batchesPerThread;
        final int lastBatch = i == (numThreads - 1) ? batches.size() : firstBatch + batchesPerThread;

        futures[i] = service.submit(new Runnable() {
            @Override
            public void run() {
                for (int k = firstBatch; k < lastBatch; k++) {
                    String batchId = batchIds[k];
                    DoubleMatrix2D batchData = ComBat.this.getBatchData(sdata, batchId);
                    DoubleMatrix1D[] batchResults = ComBat.this.nonParametricFit(batchData, gammaHat.viewRow(k),
                            deltaHat.viewRow(k));
                    results.put(batchId, batchResults);
                }
            }
        });
    }

    service.shutdown();

    boolean allDone = false;
    do {
        for (Future<?> f : futures) {
            allDone = true;
            if (!f.isDone() && !f.isCancelled()) {
                allDone = false;
                break;
            }
        }
    } while (!allDone);

    for (int i = 0; i < batchIds.length; i++) {
        String batchId = batchIds[i];
        DoubleMatrix1D[] batchResults = results.get(batchId);
        for (int j = 0; j < batchResults[0].size(); j++) {
            gammastar.set(i, j, batchResults[0].get(j));
        }
        for (int j = 0; j < batchResults[1].size(); j++) {
            deltastar.set(i, j, batchResults[1].get(j));
        }
    }
}

From source file:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java

/**
 * Load bucket from disk./*from  w ww .j  av  a  2 s. com*/
 * @param queuesBuckets
 * @param bucketIndex
 * @param queuePath
 * @throws IOException
 */
private void loadBucket(ArrayList<BucketMeta> queuesBuckets, int bucketIndex, String queuePath)
        throws IOException {
    LOG.info("[MessageQueuesForDisk] is loading the [" + queuePath + " Bucket-" + bucketIndex + "] <<< size = "
            + queuesBuckets.get(bucketIndex).count + ".");
    long start = System.currentTimeMillis();
    /** Clock */
    File messagesDataFileBucket;
    FileReader frMessagesData;
    BufferedReader brMessagesData;
    messagesDataFileBucket = new File(this.messagesDataFile + "/" + queuePath + "/" + "bucket-" + bucketIndex);
    if (!messagesDataFileBucket.exists()) {
        throw new IOException("Bucket file" + messagesDataFileBucket + " does not exit!");
    }
    // Open file readers.
    frMessagesData = new FileReader(messagesDataFileBucket);
    brMessagesData = new BufferedReader(frMessagesData);
    // Read the file header.
    @SuppressWarnings("unused")
    String bucketHeader = brMessagesData.readLine();
    ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>> queueMap = queuesBuckets
            .get(bucketIndex).queueMap;
    if (queueMap == null) {
        queueMap = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>>();
    }
    String buffer;
    while ((buffer = brMessagesData.readLine()) != null) {
        String[] queueBuffer = buffer.split(Constants.KV_SPLIT_FLAG);
        if (queueBuffer[0] == "") {
            LOG.warn("[MessageQueuesForDisk] readLine = " + buffer);
        }
        String key = queueBuffer[0];
        ConcurrentLinkedQueue<IMessage> queue = queueMap.get(key);
        if (queue == null) {
            queue = stringToQueue(queueBuffer[1]);
            this.sizeOfHashMapsInMem = this.sizeOfHashMapsInMem
                    + (sizeOfRef + sizeOfInteger + sizeOfEmptyMessageQueue);
        } else {
            queue.addAll(stringToQueue(queueBuffer[1]));
        }
        queueMap.put(key, queue);
    }
    queuesBuckets.get(bucketIndex).queueMap = queueMap;
    brMessagesData.close();
    frMessagesData.close();
    // Update the meta data of the bucket.
    BucketMeta meta = queuesBuckets.get(bucketIndex);
    // Update the size of messages data in memory.
    this.sizeOfMessagesDataInMem = this.sizeOfMessagesDataInMem + (meta.length - meta.lengthInMemory);
    this.countOfMessagesDataInMem = this.countOfMessagesDataInMem + (meta.count - meta.countInMemory);
    meta.onDiskFlag = false;
    meta.lengthInMemory = meta.length;
    meta.countInMemory = meta.count;
    queuesBuckets.set(bucketIndex, meta);
    if (!messagesDataFileBucket.delete()) {
        throw new IOException("Bucket file delete failed!");
    }
    this.readDiskTime = this.readDiskTime + (System.currentTimeMillis() - start);
    /** Clock */
}

From source file:org.wso2.andes.kernel.OnflightMessageTracker.java

/**
 * Track that this message is buffered. Return true if eligible to buffer
 *
 * @param slot                 slot message being read in
 * @param andesMessageMetadata metadata to buffer
 * @return eligibility to buffer//w  w w . j a  va  2 s.com
 */
public boolean addMessageToBufferingTracker(Slot slot, AndesMessageMetadata andesMessageMetadata) {
    long messageID = andesMessageMetadata.getMessageID();
    boolean isOKToBuffer;
    if (log.isDebugEnabled()) {
        log.debug("Buffering message id = " + messageID + " slot = " + slot.toString());
    }
    String slotID = slot.getId();
    ConcurrentHashMap<Long, MsgData> messagesOfSlot = messageBufferingTracker.get(slotID);
    if (messagesOfSlot == null) {
        messagesOfSlot = new ConcurrentHashMap<Long, MsgData>();
        messageBufferingTracker.put(slotID, messagesOfSlot);
        // track destination to slot
        // use this map to remove messageBufferingTracker when subscriber close before receive all messages in slot
        Set<Slot> subscriptionSlots = subscriptionSlotTracker.get(slot.getDestinationOfMessagesInSlot());
        if (subscriptionSlots == null) {
            Set<Slot> newTrackedSlots = new HashSet<Slot>();
            newTrackedSlots.add(slot);
            subscriptionSlotTracker.put(slot.getDestinationOfMessagesInSlot(), newTrackedSlots);
        } else {
            subscriptionSlots.add(slot);
            subscriptionSlotTracker.put(slot.getDestinationOfMessagesInSlot(), subscriptionSlots);
        }
    }
    MsgData trackingData = messagesOfSlot.get(messageID);
    if (trackingData == null) {
        trackingData = new MsgData(messageID, slot, slot.getDestinationOfMessagesInSlot(),
                System.currentTimeMillis(), andesMessageMetadata.getExpirationTime(), MessageStatus.BUFFERED,
                andesMessageMetadata.getArrivalTime());
        msgId2MsgData.put(messageID, trackingData);
        messagesOfSlot.put(messageID, trackingData);
        isOKToBuffer = true;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Buffering rejected message id = " + messageID);
        }
        isOKToBuffer = false;
    }
    return isOKToBuffer;
}