Example usage for java.util.concurrent BlockingQueue size

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

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this collection.

Usage

From source file:org.apache.camel.impl.DefaultServicePool.java

public synchronized Service addAndAcquire(Key key, Service service) {
    BlockingQueue<Service> entry = pool.get(key);
    if (entry == null) {
        entry = new ArrayBlockingQueue<Service>(capacity);
        pool.put(key, entry);//from ww w. jav a  2s. c  o m
    }
    if (log.isTraceEnabled()) {
        log.trace("AddAndAcquire key: " + key + " service: " + service);
    }

    // test if queue will be full
    if (entry.size() >= capacity) {
        throw new IllegalStateException("Queue full");
    }
    return service;
}

From source file:org.nuxeo.ecm.core.work.MemoryWorkQueuing.java

protected synchronized int getScheduledSize(String queueId) {
    BlockingQueue<Runnable> scheduled = allScheduled.get(queueId);
    return scheduled == null ? 0 : scheduled.size();
}

From source file:org.nuxeo.ecm.core.work.MemoryWorkQueuing.java

protected List<Work> listScheduled(String queueId) {
    BlockingQueue<Runnable> scheduled = getScheduledQueue(queueId);
    List<Work> list = new ArrayList<Work>(scheduled.size());
    for (Runnable r : scheduled) {
        Work w = WorkHolder.getWork(r);//from w w w.  j  av a2s  .  c  om
        list.add(w);
    }
    return list;
}

From source file:org.nuxeo.ecm.core.work.MemoryWorkQueuing.java

protected List<String> listScheduledIds(String queueId) {
    BlockingQueue<Runnable> scheduled = getScheduledQueue(queueId);
    List<String> list = new ArrayList<String>(scheduled.size());
    for (Runnable r : scheduled) {
        Work w = WorkHolder.getWork(r);//from w w w . j a  v  a 2  s  .  c  om
        list.add(w.getId());
    }
    return list;
}

From source file:voldemort.store.cachestore.impl.ChannelStore.java

public void close(BlockingQueue delayQueue) {
    if (delayWrite) {
        if (delayQueue.size() == 0) {
            logger.info("delayQueue is empty");
            return;
        } else {//  w w w  .  ja  v  a  2 s. c om

            int size = delayQueue.size();
            for (int i = 0; i < size; i++) {
                try {
                    Thread.sleep(200L);
                    logger.info("delayQueue size " + delayQueue.size() + " i =" + i);
                    // return when there is no item in queue
                    if (delayQueue.size() == 0) {
                        logger.info("delayQueue is empty");
                        return;
                    }
                } catch (Exception ex) {
                    // swallow
                }
            }
            logger.error("after " + size / 5 + " seconds, buffer size " + delayQueue.size());
        }
    } else
        close();

}

From source file:org.apache.nifi.processor.util.listen.dispatcher.DatagramChannelDispatcher.java

public DatagramChannelDispatcher(final EventFactory<E> eventFactory, final BlockingQueue<ByteBuffer> bufferPool,
        final BlockingQueue<E> events, final ComponentLog logger, final String sendingHost,
        final Integer sendingPort) {
    this.eventFactory = eventFactory;
    this.bufferPool = bufferPool;
    this.logger = logger;
    this.sendingHost = sendingHost;
    this.sendingPort = sendingPort;
    this.events = new EventQueue<>(events, logger);

    if (bufferPool == null || bufferPool.size() == 0) {
        throw new IllegalArgumentException("A pool of available ByteBuffers is required");
    }/*www  . jav  a2  s .  c o  m*/
}

From source file:com.opengamma.bbg.replay.BloombergTickWriter.java

/**
 * /*from w w  w  . j a v  a2s. c  o  m*/
 */
private void writeOutSecurityMapQueue() {
    for (Entry<String, BlockingQueue<FudgeMsg>> entry : _securityMapQueue.entrySet()) {
        String security = entry.getKey();
        BlockingQueue<FudgeMsg> queue = entry.getValue();
        if (queue.isEmpty()) {
            continue;
        }
        List<FudgeMsg> tickMsgList = new ArrayList<FudgeMsg>(queue.size());
        queue.drainTo(tickMsgList);
        String buid = getBloombergBUID(security);

        //get first message
        FudgeMsg tickMsg = tickMsgList.get(0);
        Long epochMillis = tickMsg.getLong(RECEIVED_TS_KEY);

        File dir = buildSecurityDirectory(buid, epochMillis);
        if (!dir.exists()) {
            createDirectory(dir);
        }
        writeSecurityTicks(dir, buid, security, tickMsgList);
        tickMsgList.clear();
        tickMsgList = null;
    }
}

From source file:org.apache.falcon.service.FeedSLAMonitoringService.java

@SuppressWarnings("unchecked")
private void deserialize(Path path) throws FalconException {
    try {//from   w w  w  .  j a  v  a  2s.c  o m
        Map<String, Object> state = deserializeInternal(path);
        pendingInstances = new ConcurrentHashMap<>();
        Map<Pair<String, String>, BlockingQueue<Date>> pendingInstancesCopy = (Map<Pair<String, String>, BlockingQueue<Date>>) state
                .get("pendingInstances");
        // queue size can change during restarts, hence copy
        for (Map.Entry<Pair<String, String>, BlockingQueue<Date>> entry : pendingInstancesCopy.entrySet()) {
            BlockingQueue<Date> value = new LinkedBlockingQueue<>(queueSize);
            BlockingQueue<Date> oldValue = entry.getValue();
            LOG.debug("Number of old instances:{}, new queue size:{}", oldValue.size(), queueSize);
            while (!oldValue.isEmpty()) {
                Date instance = oldValue.remove();
                if (value.size() == queueSize) { // if full
                    LOG.debug("Deserialization: Removing value={} for <feed,cluster>={}", value.peek(),
                            entry.getKey());
                    value.remove();
                }
                LOG.debug("Deserialization Adding: key={} to <feed,cluster>={}", entry.getKey(), instance);
                value.add(instance);
            }
            pendingInstances.put(entry.getKey(), value);
        }
        lastCheckedAt = new Date((Long) state.get("lastCheckedAt"));
        lastSerializedAt = new Date((Long) state.get("lastSerializedAt"));
        monitoredFeeds = new ConcurrentHashSet<>(); // will be populated on the onLoad of entities.
        LOG.debug("Restored the service from old state.");
    } catch (IOException | ClassNotFoundException e) {
        throw new FalconException("Couldn't deserialize the old state", e);
    }
}

From source file:com.google.gplus.provider.TestGPlusUserActivityCollector.java

/**
 * Creates a randomized activity and randomized date range.
 * The activity feed is separated into three chunks,
 * |. . . data too recent to be in date range . . .||. . . data in date range. . .||. . . data too old to be in date range|
 * [index 0, ............................................................................................., index length-1]
 * Inside of those chunks data has no order, but the list is ordered by those three chunks.
 *
 * The test will check to see if the num of data in the date range make onto the output queue.
 *//* ww  w.ja  va 2 s .  co m*/
@Test
@Repeat(iterations = 3)
public void testWithBeforeAndAfterDates() throws InterruptedException {
    //initialize counts assuming no date ranges will be used
    int numActivities = randomIntBetween(0, 1000);
    int numActivitiesInDateRange = numActivities;
    int numberOutOfRange = 0;
    int numBerforeRange = 0;
    int numAfterRange = 0;
    //determine if date ranges will be used
    DateTime beforeDate = null;
    DateTime afterDate = null;
    if (randomInt() % 2 == 0) {
        beforeDate = DateTime.now().minusDays(randomIntBetween(1, 5));
    }
    if (randomInt() % 2 == 0) {
        if (beforeDate == null) {
            afterDate = DateTime.now().minusDays(randomIntBetween(1, 10));
        } else {
            afterDate = beforeDate.minusDays(randomIntBetween(1, 10));
        }
    }
    //update counts if date ranges are going to be used.
    if (beforeDate != null || afterDate != null) { //assign amount to be in range
        numActivitiesInDateRange = randomIntBetween(0, numActivities);
        numberOutOfRange = numActivities - numActivitiesInDateRange;
    }
    if (beforeDate == null && afterDate != null) { //assign all out of range to be before the start of the range
        numBerforeRange = numberOutOfRange;
    } else if (beforeDate != null && afterDate == null) { //assign all out of range to be after the start of the range
        numAfterRange = numberOutOfRange;
    } else if (beforeDate != null && afterDate != null) { //assign half before range and half after the range
        numAfterRange = (numberOutOfRange / 2) + (numberOutOfRange % 2);
        numBerforeRange = numberOutOfRange / 2;
    }

    Plus plus = createMockPlus(numBerforeRange, numAfterRange, numActivitiesInDateRange, afterDate, beforeDate);
    BackOffStrategy strategy = new ConstantTimeBackOffStrategy(1);
    BlockingQueue<StreamsDatum> datums = new LinkedBlockingQueue<>();
    UserInfo userInfo = new UserInfo();
    userInfo.setUserId("A");
    userInfo.setAfterDate(afterDate);
    userInfo.setBeforeDate(beforeDate);
    GPlusUserActivityCollector collector = new GPlusUserActivityCollector(plus, datums, strategy, userInfo);
    collector.run();

    assertEquals(numActivitiesInDateRange, datums.size());
    while (!datums.isEmpty()) {
        StreamsDatum datum = datums.take();
        assertNotNull(datum);
        assertNotNull(datum.getDocument());
        assertTrue(datum.getDocument() instanceof String);
        assertTrue(((String) datum.getDocument()).contains(IN_RANGE_IDENTIFIER)); //only in range documents are on the out going queue.
    }
}

From source file:net.centro.rtb.monitoringcenter.MetricCollectorImpl.java

@Override
public <T> BlockingQueue<T> instrumentBlockingQueue(final BlockingQueue<T> blockingQueue, String topLevelName,
        String... additionalNames) {
    validateInstrumentationInputParams(blockingQueue, "blockingQueue", topLevelName);

    String queueNamespace = MetricNamingUtil.join(topLevelName, additionalNames);

    registerGauge(new Gauge<Integer>() {
        @Override//  w  w w  .j ava2s.c  o  m
        public Integer getValue() {
            return blockingQueue.size();
        }
    }, MetricNamingUtil.join(queueNamespace, "size"));

    registerGauge(new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return blockingQueue.remainingCapacity();
        }
    }, MetricNamingUtil.join(queueNamespace, "remainingCapacity"));

    return blockingQueue;
}