Example usage for java.util.concurrent ConcurrentLinkedQueue size

List of usage examples for java.util.concurrent ConcurrentLinkedQueue size

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentLinkedQueue size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this queue.

Usage

From source file:org.sunnycode.zkws.socketio.impl.IOConnection.java

/**
 * Transport connected./*from  www . j a  v a  2  s  . co m*/
 * 
 * {@link IOTransport} calls this when a connection is established.
 */
public synchronized void transportConnected() {
    setState(STATE_READY);
    if (reconnectTask != null) {
        reconnectTask.cancel();
        reconnectTask = null;
    }
    resetTimeout();
    if (transport.canSendBulk()) {
        ConcurrentLinkedQueue<String> outputBuffer = this.outputBuffer;
        this.outputBuffer = new ConcurrentLinkedQueue<String>();
        try {
            // DEBUG
            String[] texts = outputBuffer.toArray(new String[outputBuffer.size()]);
            logger.info("Bulk start:");
            for (String text : texts) {
                logger.info("> " + text);
            }
            logger.info("Bulk end");
            // DEBUG END
            transport.sendBulk(texts);
        } catch (IOException e) {
            this.outputBuffer = outputBuffer;
        }
    } else {
        String text;
        while ((text = outputBuffer.poll()) != null)
            sendPlain(text);
    }
    this.keepAliveInQueue = false;
}

From source file:server.Folder.java

/**
 * Copy all versions of the objects found in a folder. This will create the complete object tree of
 * the objects, so if an object has ancestors or descendants in other folders, those will be copied, too.
 * @param folderContent the content of the folder which should be copied completely.
 * @param otc a ObjectTreeCopier which is configured with a validator and correct activeUser.
 * @param croakOnError if true, stop in case of an error and return a CopyResult which contains the events so far.
 * @return a copyResult containing a collection of all failed and successful attempts at copying the
 * folder's contents.//  w  w w .j a v a 2s. c  o m
 */
CopyResult copyAllVersions(Collection<ObjectSystemData> folderContent, ObjectTreeCopier otc,
        Boolean croakOnError) {
    ObjectSystemDataDAO oDao = daoFactory.getObjectSystemDataDAO(HibernateSession.getLocalEntityManager());
    CopyResult copyResult = new CopyResult();

    ConcurrentLinkedQueue<ObjectSystemData> conQueue = new ConcurrentLinkedQueue<ObjectSystemData>();
    conQueue.addAll(folderContent);
    log.debug("starting to copy " + conQueue.size() + " objects");

    for (ObjectSystemData source : conQueue) {
        //            otc.resetCopyResult();
        try {
            // create a full copy of the whole object tree:
            otc.createFullCopy(source);
            copyResult.addCopyResult(otc.getCopyResult());
        } catch (Exception ex) {
            log.debug("objectTreeCopy failed for id " + source.getId(), ex);
            // copy failed - now we have to cleanup and remove the already created copies:
            ObjectSystemData brokenCopy = otc.getCopyCache().get(source);
            if (brokenCopy != null) {
                // we should nuke all other objects with the same root,
                // as they won't be amendable to a copy operation either.
                for (ObjectSystemData osd : conQueue) {
                    if (osd.getRoot().equals(brokenCopy.getRoot())) {
                        conQueue.remove(osd);
                    }
                }

                // recursively delete the broken object tree.
                oDao.delete(brokenCopy.getRoot(), true, true);
            }

            log.debug("cleanup complete.");
            copyResult.addFailure(source, new CinnamonException(ex));
            if (croakOnError) {
                return copyResult;
            }
        }
    }
    return copyResult;
}

From source file:com.xeiam.xchange.streaming.socketio.IOConnection.java

/**
 * Transport connected. {@link IOTransport} calls this when a connection is established.
 *///from w w w  .  j a va 2  s  .co m
public void transportConnected() {

    setState(STATE_READY);
    if (reconnectTask != null) {
        reconnectTask.cancel();
        reconnectTask = null;
    }
    resetTimeout();
    synchronized (outputBuffer) {
        if (transport.canSendBulk()) {
            ConcurrentLinkedQueue<String> outputBuffer = this.outputBuffer;
            this.outputBuffer = new ConcurrentLinkedQueue<String>();
            try {
                // DEBUG
                String[] texts = outputBuffer.toArray(new String[outputBuffer.size()]);
                log.debug("Bulk start:");
                for (String text : texts) {
                    log.debug("> " + text);
                }
                log.debug("Bulk end");
                // DEBUG END
                transport.sendBulk(texts);
            } catch (IOException e) {
                this.outputBuffer = outputBuffer;
            }
        } else {
            String text;
            while ((text = outputBuffer.poll()) != null) {
                sendPlain(text);
            }
        }
        this.keepAliveInQueue = false;
    }
}

From source file:org.restcomm.app.qoslib.Services.Events.EventUploader.java

/**
 * Persists the queue of events to the phone's preferences
 *///ww  w.j a  va 2 s  .  com
protected void saveEvents(ConcurrentLinkedQueue<EventDataEnvelope> eventQueue) {
    //JSONArray jsonQueue= new JSONArray();
    if (eventQueue == null)
        return;
    StringBuffer sb = new StringBuffer();
    sb.append("[");
    Gson gson = new Gson();
    // remove the oldest events until queue is below 400
    while (eventQueue.size() > 300)
        eventQueue.poll();

    for (EventDataEnvelope eventEnv : eventQueue) {
        try {
            String strJSON = gson.toJson(eventEnv);
            sb.append(strJSON);
            sb.append(",");
            //JSONObject evtJSON =  new JSONObject(strJSON);
            //jsonQueue.put(evtJSON);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "persistQueue", "failed to persist event request",
                    e);
        }
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append("]");

    SharedPreferences preferenceSettings = MainService.getSecurePreferences(owner);
    String stringQueue = sb.toString();//  jsonQueue.toString();

    preferenceSettings.edit().putString(PreferenceKeys.Miscellaneous.EVENTS_QUEUE, stringQueue).commit();
}

From source file:de.mmbbs.io.socket.IOConnection.java

/**
 * Transport connected./*  w ww  .  j a v a  2s. co  m*/
 * 
 * {@link IOTransport} calls this when a connection is established.
 */
public synchronized void transportConnected() {
    setState(STATE_READY);
    if (reconnectTask != null) {
        reconnectTask.cancel();
        reconnectTask = null;
    }
    if (heartBeatTask != null) {
        heartBeatTask.cancel();
    }
    heartBeatTask = new HeartBeatTask(); // heartbeat loop
    backgroundTimer.schedule(heartBeatTask, heartbeatTimeout, heartbeatTimeout);
    resetTimeout();
    if (transport.canSendBulk()) {
        ConcurrentLinkedQueue<String> outputBuffer = this.outputBuffer;
        this.outputBuffer = new ConcurrentLinkedQueue<String>();
        try {
            // DEBUG
            String[] texts = outputBuffer.toArray(new String[outputBuffer.size()]);
            logger.info("Bulk start:");
            for (String text : texts) {
                logger.info("> " + text);
            }
            logger.info("Bulk end");
            // DEBUG END
            transport.sendBulk(texts);
        } catch (IOException e) {
            this.outputBuffer = outputBuffer;
        }
    } else {
        String text;
        while ((text = outputBuffer.poll()) != null)
            sendPlain(text);
    }
    this.keepAliveInQueue = false;
}

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

@Override
public int getOutgoingQueuesSize() {
    int size = 0;
    Entry<String, ConcurrentLinkedQueue<IMessage>> entry = null;
    Iterator<Entry<String, ConcurrentLinkedQueue<IMessage>>> it = this.outgoingQueues.entrySet().iterator();
    ConcurrentLinkedQueue<IMessage> tmpQueue = null;
    while (it.hasNext()) {
        entry = it.next();/*ww  w.jav a  2 s .c  o  m*/
        tmpQueue = entry.getValue();
        size = size + tmpQueue.size();
    }
    return size;
}

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

/**
 * Current strategy is get the max outgoing queue in memory.
 *//*from   w w  w.j a  v  a 2s  . com*/
@Override
public String getMaxOutgoingQueueIndex() {
    String maxIndex = null;
    long maxSize = 0;
    synchronized (this.outgoingQueues) {
        Entry<String, ConcurrentLinkedQueue<IMessage>> entry = null;
        Iterator<Entry<String, ConcurrentLinkedQueue<IMessage>>> it = this.outgoingQueues.entrySet().iterator();
        ConcurrentLinkedQueue<IMessage> tmpQueue = null;
        while (it.hasNext()) {
            entry = it.next();
            tmpQueue = entry.getValue();
            if (tmpQueue.size() > maxSize) {
                maxSize = tmpQueue.size();
                maxIndex = entry.getKey();
            }
        }
    }
    return maxIndex;
}

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

@Override
public int getOutgoingQueueSize(String index) {
    ConcurrentLinkedQueue<IMessage> queue = null;
    synchronized (this.outgoingQueues) {
        queue = this.outgoingQueues.get(index);
    }/*ww w .  j a va2  s .  c o  m*/
    if (queue != null) {
        return queue.size();
    } else {
        return 0;
    }
}

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

@Override
public void clearOutgoingQueues() {
    Entry<String, ConcurrentLinkedQueue<IMessage>> entry = null;
    Iterator<Entry<String, ConcurrentLinkedQueue<IMessage>>> it = this.outgoingQueues.entrySet().iterator();
    ConcurrentLinkedQueue<IMessage> tmpQueue = null;
    int tmpCount = 0;
    while (it.hasNext()) {
        entry = it.next();// w ww .  j  av  a 2 s .  co m
        tmpQueue = entry.getValue();
        tmpCount = tmpQueue.size();
        this.sizeOfMessagesDataInMem = this.sizeOfMessagesDataInMem - (tmpCount * this.sizeOfMessage);
        this.countOfMessagesDataInMem = this.countOfMessagesDataInMem - tmpCount;
        this.sizeOfHashMapsInMem = this.sizeOfHashMapsInMem
                - (sizeOfRef * 2 + (entry.getKey().length() * sizeOfChar) + sizeOfEmptyMessageQueue);
    }
    this.outgoingQueues.clear();
}

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

/** run method. */
public void run() {
    LOG.info("[CombinerTool] Start!");
    long time = 0;
    long totalBeforeSize = 0;
    long totalAfterSize = 0;
    String outgoIndex = null;//from  w w w  .j a v  a 2 s .  c o m
    ConcurrentLinkedQueue<IMessage> maxQueue = null;
    int maxSize = 0;
    int lastCount = 0;
    while (!this.sender.getNoMoreMessagesFlag()) {
        outgoIndex = this.messageQueues.getMaxOutgoingQueueIndex();
        if (outgoIndex != null) {
            maxSize = this.messageQueues.getOutgoingQueueSize(outgoIndex);
        }
        lastCount = (this.combinedCountsMap.get(outgoIndex) == null ? 0
                : this.combinedCountsMap.get(outgoIndex));
        // If new updated size is over the threshold
        if ((maxSize - lastCount) > this.combineThreshold) {
            // Get the queue out of the map.
            maxQueue = this.messageQueues.removeOutgoingQueue(outgoIndex);
            if (maxQueue == null) {
                continue;
            }
            long start = System.currentTimeMillis();
            /* Clock */
            // Combine the messages.
            maxQueue = combine(maxQueue);
            long end = System.currentTimeMillis();
            /* Clock */
            time = time + end - start;
            int maxSizeBefore = maxSize;
            totalBeforeSize += maxSizeBefore;
            maxSize = maxQueue.size();
            totalAfterSize += maxSize;
            // Note the count after combination.
            this.combinedCountsMap.put(outgoIndex, maxQueue.size());
            // Put the combined messages back to the outgoing queue.
            Iterator<IMessage> iter = maxQueue.iterator();
            while (iter.hasNext()) {
                this.messageQueues.outgoAMessage(outgoIndex, iter.next());
            }
            maxQueue.clear();
        } else {
            try {
                // Wait for 500ms until next check.
                Thread.sleep(500);
            } catch (Exception e) {
                throw new RuntimeException("[[CombinerTool] run exception", e);
            }
        }
    }
    LOG.info("[CombinerTool] has combined totally (" + totalBeforeSize + ") messages into (" + totalAfterSize
            + "). Compression rate = " + (float) totalAfterSize * 100 / totalBeforeSize + "%.");
    LOG.info("[CombinerTool] has used time: " + time / TIME_CHANGE + " seconds totally!");
    LOG.info("[CombinerTool] Die!");
}