java.util.concurrent.ArrayBlockingQueue

Here are the examples of the java api class java.util.concurrent.ArrayBlockingQueue taken from open source projects.

1. ArrayBlockingQueueTest#testDrainTo()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * drainTo(c) empties queue into another collection c
     */
public void testDrainTo() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    ArrayList l = new ArrayList();
    q.drainTo(l);
    assertEquals(0, q.size());
    assertEquals(SIZE, l.size());
    for (int i = 0; i < SIZE; ++i) assertEquals(l.get(i), new Integer(i));
    q.add(zero);
    q.add(one);
    assertFalse(q.isEmpty());
    assertTrue(q.contains(zero));
    assertTrue(q.contains(one));
    l.clear();
    q.drainTo(l);
    assertEquals(0, q.size());
    assertEquals(2, l.size());
    for (int i = 0; i < 2; ++i) assertEquals(l.get(i), new Integer(i));
}

2. ArrayBlockingQueueTest#testDrainTo()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * drainTo(c) empties queue into another collection c
     */
public void testDrainTo() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    ArrayList l = new ArrayList();
    q.drainTo(l);
    assertEquals(0, q.size());
    assertEquals(SIZE, l.size());
    for (int i = 0; i < SIZE; ++i) assertEquals(l.get(i), new Integer(i));
    q.add(zero);
    q.add(one);
    assertFalse(q.isEmpty());
    assertTrue(q.contains(zero));
    assertTrue(q.contains(one));
    l.clear();
    q.drainTo(l);
    assertEquals(0, q.size());
    assertEquals(2, l.size());
    for (int i = 0; i < 2; ++i) assertEquals(l.get(i), new Integer(i));
}

3. ArrayBlockingQueueTest#testClear()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * clear removes all elements
     */
public void testClear() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    q.clear();
    assertTrue(q.isEmpty());
    assertEquals(0, q.size());
    assertEquals(SIZE, q.remainingCapacity());
    q.add(one);
    assertFalse(q.isEmpty());
    assertTrue(q.contains(one));
    q.clear();
    assertTrue(q.isEmpty());
}

4. ArrayBlockingQueueTest#testIteratorRemove()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * iterator.remove removes current element
     */
public void testIteratorRemove() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(two);
    q.add(one);
    q.add(three);
    Iterator it = q.iterator();
    it.next();
    it.remove();
    it = q.iterator();
    assertSame(it.next(), one);
    assertSame(it.next(), three);
    assertFalse(it.hasNext());
}

5. ArrayBlockingQueueTest#testIteratorOrdering()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * iterator ordering is FIFO
     */
public void testIteratorOrdering() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(one);
    q.add(two);
    q.add(three);
    assertEquals("queue should be full", 0, q.remainingCapacity());
    int k = 0;
    for (Iterator it = q.iterator(); it.hasNext(); ) {
        assertEquals(++k, it.next());
    }
    assertEquals(3, k);
}

6. ArrayBlockingQueueTest#testClear()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * clear removes all elements
     */
public void testClear() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    q.clear();
    assertTrue(q.isEmpty());
    assertEquals(0, q.size());
    assertEquals(SIZE, q.remainingCapacity());
    q.add(one);
    assertFalse(q.isEmpty());
    assertTrue(q.contains(one));
    q.clear();
    assertTrue(q.isEmpty());
}

7. ArrayBlockingQueueTest#testIteratorRemove()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * iterator.remove removes current element
     */
public void testIteratorRemove() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(two);
    q.add(one);
    q.add(three);
    Iterator it = q.iterator();
    it.next();
    it.remove();
    it = q.iterator();
    assertSame(it.next(), one);
    assertSame(it.next(), three);
    assertFalse(it.hasNext());
}

8. ArrayBlockingQueueTest#testIteratorOrdering()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * iterator ordering is FIFO
     */
public void testIteratorOrdering() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(one);
    q.add(two);
    q.add(three);
    assertEquals("queue should be full", 0, q.remainingCapacity());
    int k = 0;
    for (Iterator it = q.iterator(); it.hasNext(); ) {
        assertEquals(++k, it.next());
    }
    assertEquals(3, k);
}

9. ArrayBlockingQueueTest#testOfferInExecutor()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * offer transfers elements across Executor tasks
     */
public void testOfferInExecutor() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    q.add(one);
    q.add(two);
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(executor)) {
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                assertFalse(q.offer(three));
                threadsStarted.await();
                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
                assertEquals(0, q.remainingCapacity());
            }
        });
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                threadsStarted.await();
                assertEquals(0, q.remainingCapacity());
                assertSame(one, q.take());
            }
        });
    }
}

10. ArrayBlockingQueueTest#testOfferInExecutor()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * offer transfers elements across Executor tasks
     */
public void testOfferInExecutor() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    q.add(one);
    q.add(two);
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(executor)) {
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                assertFalse(q.offer(three));
                threadsStarted.await();
                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
                assertEquals(0, q.remainingCapacity());
            }
        });
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                threadsStarted.await();
                assertEquals(0, q.remainingCapacity());
                assertSame(one, q.take());
            }
        });
    }
}

11. ArrayBlockingQueueTest#testRetainAll()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * retainAll(c) retains only those elements of c and reports true if changed
     */
public void testRetainAll() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    ArrayBlockingQueue p = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        boolean changed = q.retainAll(p);
        if (i == 0)
            assertFalse(changed);
        else
            assertTrue(changed);
        assertTrue(q.containsAll(p));
        assertEquals(SIZE - i, q.size());
        p.remove();
    }
}

12. ArrayBlockingQueueTest#testDrainToWithActivePut()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * drainTo empties full queue, unblocking a waiting put.
     */
public void testDrainToWithActivePut() throws InterruptedException {
    final ArrayBlockingQueue q = populatedQueue(SIZE);
    Thread t = new Thread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            q.put(new Integer(SIZE + 1));
        }
    });
    t.start();
    ArrayList l = new ArrayList();
    q.drainTo(l);
    assertTrue(l.size() >= SIZE);
    for (int i = 0; i < SIZE; ++i) assertEquals(l.get(i), new Integer(i));
    t.join();
    assertTrue(q.size() + l.size() >= SIZE);
}

13. ArrayBlockingQueueTest#testRetainAll()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * retainAll(c) retains only those elements of c and reports true if changed
     */
public void testRetainAll() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    ArrayBlockingQueue p = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        boolean changed = q.retainAll(p);
        if (i == 0)
            assertFalse(changed);
        else
            assertTrue(changed);
        assertTrue(q.containsAll(p));
        assertEquals(SIZE - i, q.size());
        p.remove();
    }
}

14. ArrayBlockingQueueTest#testDrainToWithActivePut()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * drainTo empties full queue, unblocking a waiting put.
     */
public void testDrainToWithActivePut() throws InterruptedException {
    final ArrayBlockingQueue q = populatedQueue(SIZE);
    Thread t = new Thread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            q.put(new Integer(SIZE + 1));
        }
    });
    t.start();
    ArrayList l = new ArrayList();
    q.drainTo(l);
    assertTrue(l.size() >= SIZE);
    for (int i = 0; i < SIZE; ++i) assertEquals(l.get(i), new Integer(i));
    t.join();
    assertTrue(q.size() + l.size() >= SIZE);
}

15. PropertiesLoginModuleRaceConditionTest#before()

View license
@Before
public void before() throws FileNotFoundException, IOException {
    createUsers();
    createGroups();
    options = new HashMap<>();
    // Used to simplify reproduction of the
    options.put("reload", "true");
    // race condition
    options.put("org.apache.activemq.jaas.properties.user", USERS_FILE);
    options.put("org.apache.activemq.jaas.properties.role", ROLES_FILE);
    options.put("baseDir", temp.getRoot().getAbsolutePath());
    errors = new ArrayBlockingQueue<>(processorCount());
    pool = Executors.newFixedThreadPool(processorCount(), ActiveMQThreadFactory.defaultThreadFactory());
    callback = new JaasCallbackHandler(USERNAME, PASSWORD, null);
}

16. StompTestBase#setUp()

Project: activemq-artemis
Source File: StompTestBase.java
View license
// Implementation methods
// -------------------------------------------------------------------------
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    priorityQueue = new ArrayBlockingQueue<>(1000);
    if (autoCreateServer) {
        server = createServer();
        addServer(server.getActiveMQServer());
        server.start();
        connectionFactory = createConnectionFactory();
        createBootstrap();
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = session.createQueue(getQueueName());
        topic = session.createTopic(getTopicName());
        connection.start();
    }
}

17. SDCWebSocketServlet#init()

View license
@Override
public void init() throws ServletException {
    super.init();
    queue = new ArrayBlockingQueue<>(10000);
    executorService = new SafeScheduledExecutorService(1, "WebSocket");
    executorService.submit(new Runnable() {

        @Override
        public void run() {
            while (!executorService.isShutdown()) {
                try {
                    WebSocketMessage message = queue.poll(100, TimeUnit.MILLISECONDS);
                    if (message != null) {
                        message.send();
                    }
                } catch (InterruptedException ex) {
                } catch (IOExceptionWebSocketException |  ex) {
                    LOG.warn("Failed to send WebSocket message: {}", ex.toString(), ex);
                }
            }
        }
    });
}

18. ArrayBlockingQueueTest#testTimedOffer()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed offer times out if full and elements not taken
     */
public void testTimedOffer() throws InterruptedException {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            q.put(new Object());
            q.put(new Object());
            long startTime = System.nanoTime();
            assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
            pleaseInterrupt.countDown();
            try {
                q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
                shouldThrow();
            } catch (InterruptedException success) {
            }
        }
    });
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
}

19. ArrayBlockingQueueTest#testTimedPoll()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed poll with nonzero timeout succeeds when non-empty, else times out
     */
public void testTimedPoll() throws InterruptedException {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        long startTime = System.nanoTime();
        assertEquals(i, q.poll(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
    }
    long startTime = System.nanoTime();
    assertNull(q.poll(timeoutMillis(), MILLISECONDS));
    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
    checkEmpty(q);
}

20. ArrayBlockingQueueTest#testToArray()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * toArray() contains all elements in FIFO order
     */
public void testToArray() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        q.add(i);
    }
    // Provoke wraparound
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        assertEquals(i, q.poll());
        checkToArray(q);
        q.add(SIZE + i);
    }
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        assertEquals(SIZE + i, q.poll());
    }
}

21. ArrayBlockingQueueTest#testToArray2()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * toArray(a) contains all elements in FIFO order
     */
public void testToArray2() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; i++) {
        checkToArray2(q);
        q.add(i);
    }
    // Provoke wraparound
    for (int i = 0; i < SIZE; i++) {
        checkToArray2(q);
        assertEquals(i, q.poll());
        checkToArray2(q);
        q.add(SIZE + i);
    }
    for (int i = 0; i < SIZE; i++) {
        checkToArray2(q);
        assertEquals(SIZE + i, q.poll());
    }
}

22. ArrayBlockingQueueTest#testIterator()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * iterator iterates through all elements
     */
public void testIterator() throws InterruptedException {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    Iterator it = q.iterator();
    int i;
    for (i = 0; it.hasNext(); i++) assertTrue(q.contains(it.next()));
    assertEquals(i, SIZE);
    assertIteratorExhausted(it);
    it = q.iterator();
    for (i = 0; it.hasNext(); i++) assertEquals(it.next(), q.take());
    assertEquals(i, SIZE);
    assertIteratorExhausted(it);
}

23. ArrayBlockingQueueTest#testPollInExecutor()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed poll retrieves elements across Executor threads
     */
public void testPollInExecutor() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(executor)) {
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                assertNull(q.poll());
                threadsStarted.await();
                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
                checkEmpty(q);
            }
        });
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                threadsStarted.await();
                q.put(one);
            }
        });
    }
}

24. ArrayBlockingQueueTest#testDrainToN()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * drainTo(c, n) empties first min(n, size) elements of queue into c
     */
public void testDrainToN() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE * 2);
    for (int i = 0; i < SIZE + 2; ++i) {
        for (int j = 0; j < SIZE; j++) assertTrue(q.offer(new Integer(j)));
        ArrayList l = new ArrayList();
        q.drainTo(l, i);
        int k = (i < SIZE) ? i : SIZE;
        assertEquals(k, l.size());
        assertEquals(SIZE - k, q.size());
        for (int j = 0; j < k; ++j) assertEquals(l.get(j), new Integer(j));
        do {
        } while (q.poll() != null);
    }
}

25. ConsoleManager#init()

Project: ngrinder
Source File: ConsoleManager.java
View license
/**
	 * Prepare console queue.
	 */
@PostConstruct
public void init() {
    int consoleSize = getConsoleSize();
    consoleQueue = new ArrayBlockingQueue<ConsoleEntry>(consoleSize);
    final String currentIP = config.getCurrentIP();
    for (int each : getAvailablePorts(currentIP, consoleSize, getConsolePortBase(), MAX_PORT_NUMBER)) {
        final ConsoleEntry e = new ConsoleEntry(config.getCurrentIP(), each);
        try {
            e.occupySocket();
            consoleQueue.add(e);
        } catch (Exception ex) {
            LOG.error("socket binding to {}:{} is failed", config.getCurrentIP(), each);
        }
    }
}

26. LsaQueueConsumerTest#testRun()

Project: onos
Source File: LsaQueueConsumerTest.java
View license
/**
     * Tests run() method.
     */
@Test
public void testRun() throws Exception {
    blockingQueue = new ArrayBlockingQueue(5);
    channel = EasyMock.createMock(Channel.class);
    ospfArea = new OspfAreaImpl();
    lsaWrapper = new LsaWrapperImpl();
    lsaWrapper.setLsaProcessing("verifyChecksum");
    blockingQueue.add(lsaWrapper);
    lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
    lsaQueueConsumer.run();
    assertThat(lsaQueueConsumer, is(notNullValue()));
}

27. LsaQueueConsumerTest#testRun1()

Project: onos
Source File: LsaQueueConsumerTest.java
View license
/**
     * Tests run() method.
     */
@Test
public void testRun1() throws Exception {
    blockingQueue = new ArrayBlockingQueue(5);
    channel = EasyMock.createMock(Channel.class);
    ospfArea = new OspfAreaImpl();
    lsaWrapper = new LsaWrapperImpl();
    routerLsa = new RouterLsa();
    routerLsa.setLsType(1);
    lsaWrapper.addLsa(OspfLsaType.ROUTER, routerLsa);
    ospfInterface = new OspfInterfaceImpl();
    ospfInterface.setState(OspfInterfaceState.DR);
    lsaWrapper.setOspfInterface(ospfInterface);
    lsaWrapper.setIsSelfOriginated(true);
    lsaHeader = new LsaHeader();
    lsaHeader.setLsType(1);
    lsaWrapper.setLsaHeader(lsaHeader);
    lsaWrapper.setLsaProcessing("refreshLsa");
    lsaWrapper.setLsdbAge(new LsdbAgeImpl(new OspfAreaImpl()));
    blockingQueue.add(lsaWrapper);
    lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
    lsaQueueConsumer.run();
    assertThat(lsaQueueConsumer, is(notNullValue()));
}

28. LsaQueueConsumerTest#testRun3()

Project: onos
Source File: LsaQueueConsumerTest.java
View license
@Test
public void testRun3() throws Exception {
    blockingQueue = new ArrayBlockingQueue(5);
    channel = EasyMock.createMock(Channel.class);
    ospfArea = new OspfAreaImpl();
    lsaWrapper = new LsaWrapperImpl();
    routerLsa = new RouterLsa();
    routerLsa.setLsType(2);
    lsaWrapper.addLsa(OspfLsaType.NETWORK, routerLsa);
    ospfInterface = new OspfInterfaceImpl();
    ospfInterface.setState(OspfInterfaceState.BDR);
    lsaWrapper.setOspfInterface(ospfInterface);
    lsaWrapper.setIsSelfOriginated(true);
    lsaHeader = new LsaHeader();
    lsaHeader.setLsType(2);
    lsaWrapper.setLsaHeader(lsaHeader);
    lsaWrapper.setLsaProcessing("refreshLsa");
    lsaWrapper.setLsdbAge(new LsdbAgeImpl(new OspfAreaImpl()));
    blockingQueue.add(lsaWrapper);
    lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
    lsaQueueConsumer.run();
    assertThat(lsaQueueConsumer, is(notNullValue()));
}

29. LsaQueueConsumerTest#testRun5()

Project: onos
Source File: LsaQueueConsumerTest.java
View license
/**
     * Tests run() method.
     */
@Test
public void testRun5() throws Exception {
    blockingQueue = new ArrayBlockingQueue(5);
    channel = EasyMock.createMock(Channel.class);
    ospfArea = new OspfAreaImpl();
    lsaWrapper = new LsaWrapperImpl();
    routerLsa = new RouterLsa();
    routerLsa.setLsType(2);
    lsaWrapper.addLsa(OspfLsaType.NETWORK, routerLsa);
    ospfInterface = new OspfInterfaceImpl();
    ospfInterface.setState(OspfInterfaceState.DR);
    lsaWrapper.setOspfInterface(ospfInterface);
    lsaWrapper.setIsSelfOriginated(true);
    lsaHeader = new LsaHeader();
    lsaHeader.setLsType(2);
    lsaWrapper.setLsaHeader(lsaHeader);
    lsaWrapper.setLsaProcessing("maxAgeLsa");
    lsaWrapper.setLsdbAge(new LsdbAgeImpl(new OspfAreaImpl()));
    blockingQueue.add(lsaWrapper);
    lsaQueueConsumer = new LsaQueueConsumer(blockingQueue, channel, ospfArea);
    lsaQueueConsumer.run();
    assertThat(lsaQueueConsumer, is(notNullValue()));
}

30. DrainToFails#testDelayQueue()

Project: openjdk
Source File: DrainToFails.java
View license
void testDelayQueue(final BlockingQueue q) throws Throwable {
    System.err.println(q.getClass().getSimpleName());
    for (int i = 0; i < CAPACITY; i++) q.add(new PDelay(i));
    ArrayBlockingQueue q2 = new ArrayBlockingQueue(SMALL);
    try {
        q.drainTo(q2, SMALL + 3);
        fail("should throw");
    } catch (IllegalStateException success) {
        equal(SMALL, q2.size());
        equal(new PDelay(0), q2.poll());
        equal(new PDelay(1), q2.poll());
        check(q2.isEmpty());
        for (int i = SMALL; i < CAPACITY; i++) equal(new PDelay(i), q.poll());
        equal(0, q.size());
    }
}

31. ArrayBlockingQueueTest#testTimedOffer()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed offer times out if full and elements not taken
     */
public void testTimedOffer() throws InterruptedException {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            q.put(new Object());
            q.put(new Object());
            long startTime = System.nanoTime();
            assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
            pleaseInterrupt.countDown();
            try {
                q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
                shouldThrow();
            } catch (InterruptedException success) {
            }
        }
    });
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
}

32. ArrayBlockingQueueTest#testTimedPoll()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed poll with nonzero timeout succeeds when non-empty, else times out
     */
public void testTimedPoll() throws InterruptedException {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        long startTime = System.nanoTime();
        assertEquals(i, q.poll(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
    }
    long startTime = System.nanoTime();
    assertNull(q.poll(timeoutMillis(), MILLISECONDS));
    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
    checkEmpty(q);
}

33. ArrayBlockingQueueTest#testToArray()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * toArray() contains all elements in FIFO order
     */
public void testToArray() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        q.add(i);
    }
    // Provoke wraparound
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        assertEquals(i, q.poll());
        checkToArray(q);
        q.add(SIZE + i);
    }
    for (int i = 0; i < SIZE; i++) {
        checkToArray(q);
        assertEquals(SIZE + i, q.poll());
    }
}

34. ArrayBlockingQueueTest#testToArray2()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * toArray(a) contains all elements in FIFO order
     */
public void testToArray2() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; i++) {
        checkToArray2(q);
        q.add(i);
    }
    // Provoke wraparound
    for (int i = 0; i < SIZE; i++) {
        checkToArray2(q);
        assertEquals(i, q.poll());
        checkToArray2(q);
        q.add(SIZE + i);
    }
    for (int i = 0; i < SIZE; i++) {
        checkToArray2(q);
        assertEquals(SIZE + i, q.poll());
    }
}

35. ArrayBlockingQueueTest#testIterator()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * iterator iterates through all elements
     */
public void testIterator() throws InterruptedException {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    Iterator it = q.iterator();
    int i;
    for (i = 0; it.hasNext(); i++) assertTrue(q.contains(it.next()));
    assertEquals(i, SIZE);
    assertIteratorExhausted(it);
    it = q.iterator();
    for (i = 0; it.hasNext(); i++) assertEquals(it.next(), q.take());
    assertEquals(i, SIZE);
    assertIteratorExhausted(it);
}

36. ArrayBlockingQueueTest#testPollInExecutor()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed poll retrieves elements across Executor threads
     */
public void testPollInExecutor() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try (PoolCleaner cleaner = cleaner(executor)) {
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                assertNull(q.poll());
                threadsStarted.await();
                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
                checkEmpty(q);
            }
        });
        executor.execute(new CheckedRunnable() {

            public void realRun() throws InterruptedException {
                threadsStarted.await();
                q.put(one);
            }
        });
    }
}

37. ArrayBlockingQueueTest#testDrainToN()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * drainTo(c, n) empties first min(n, size) elements of queue into c
     */
public void testDrainToN() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE * 2);
    for (int i = 0; i < SIZE + 2; ++i) {
        for (int j = 0; j < SIZE; j++) assertTrue(q.offer(new Integer(j)));
        ArrayList l = new ArrayList();
        q.drainTo(l, i);
        int k = (i < SIZE) ? i : SIZE;
        assertEquals(k, l.size());
        assertEquals(SIZE - k, q.size());
        for (int j = 0; j < k; ++j) assertEquals(l.get(j), new Integer(j));
        do {
        } while (q.poll() != null);
    }
}

38. GenericAsyncCoalescingStatisticsAppender#start()

View license
// --- main lifecycle methods ---
/**
     * The start method should only be called once, before the append method is called, to initialize options.
     *
     * @param handler The GroupedTimingStatisticsHandler used to process GroupedTimingStatistics created by aggregating
     *                StopWatch log message.
     */
public void start(GroupedTimingStatisticsHandler handler) {
    //start should only be called once, but just in case:
    if (drainingThread != null) {
        stopDrainingThread();
    }
    this.handler = handler;
    stopWatchParser = newStopWatchParser();
    numDiscardedMessages = 0;
    loggedMessages = new ArrayBlockingQueue<String>(getQueueSize());
    drainingThread = new Thread(new Dispatcher(), "perf4j-async-stats-appender-sink-" + getName());
    drainingThread.setDaemon(true);
    drainingThread.start();
}

39. BasicSendQueueWithTransferQueueTest#setup()

View license
@Before
public void setup() {
    queueBuilder = QueueBuilder.queueBuilder().setLinkTransferQueue().setCheckEvery(10).setBatchSize(1_000);
    queue = queueBuilder.build();
    sendQueue = queue.sendQueue();
    abq = new ArrayBlockingQueue<>(100_000);
}

40. BasicSendQueueWithTryTransferTest#setup()

View license
@Before
public void setup() {
    queueBuilder = QueueBuilder.queueBuilder().setLinkTransferQueue().setCheckEvery(10).setBatchSize(1_000).setCheckIfBusy(true).setTryTransfer(true);
    queue = queueBuilder.build();
    sendQueue = queue.sendQueue();
    abq = new ArrayBlockingQueue<>(100_000);
}

41. NoBatchQueueTest#setup()

Project: qbit
Source File: NoBatchQueueTest.java
View license
@Before
public void setup() {
    queueBuilder = QueueBuilder.queueBuilder().setLinkTransferQueue().setBatchSize(1);
    queue = queueBuilder.build();
    sendQueue = queue.sendQueue();
    abq = new ArrayBlockingQueue<>(100_000);
}

42. ArrayBlockingQueueTest#testWeaklyConsistentIteration()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Modifications do not cause iterators to fail
     */
public void testWeaklyConsistentIteration() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(one);
    q.add(two);
    q.add(three);
    for (Iterator it = q.iterator(); it.hasNext(); ) {
        q.remove();
        it.next();
    }
    assertEquals(0, q.size());
}

43. ArrayBlockingQueueTest#testWeaklyConsistentIteration()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Modifications do not cause iterators to fail
     */
public void testWeaklyConsistentIteration() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(one);
    q.add(two);
    q.add(three);
    for (Iterator it = q.iterator(); it.hasNext(); ) {
        q.remove();
        it.next();
    }
    assertEquals(0, q.size());
}

44. ArrayBlockingQueueTest#testEmptyFull()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Queue transitions from empty to full when elements added
     */
public void testEmptyFull() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    assertTrue(q.isEmpty());
    assertEquals(2, q.remainingCapacity());
    q.add(one);
    assertFalse(q.isEmpty());
    q.add(two);
    assertFalse(q.isEmpty());
    assertEquals(0, q.remainingCapacity());
    assertFalse(q.offer(three));
}

45. ArrayBlockingQueueTest#testEmptyFull()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Queue transitions from empty to full when elements added
     */
public void testEmptyFull() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(2);
    assertTrue(q.isEmpty());
    assertEquals(2, q.remainingCapacity());
    q.add(one);
    assertFalse(q.isEmpty());
    q.add(two);
    assertFalse(q.isEmpty());
    assertEquals(0, q.remainingCapacity());
    assertFalse(q.offer(three));
}

46. COMPRESS#init()

Project: JGroups
Source File: COMPRESS.java
View license
public void init() throws Exception {
    deflater_pool = new ArrayBlockingQueue<>(pool_size);
    for (int i = 0; i < pool_size; i++) deflater_pool.add(new Deflater(compression_level));
    inflater_pool = new ArrayBlockingQueue<>(pool_size);
    for (int i = 0; i < pool_size; i++) inflater_pool.add(new Inflater());
}

47. Encrypt#init()

Project: JGroups
Source File: Encrypt.java
View license
public void init() throws Exception {
    int tmp = Util.getNextHigherPowerOfTwo(cipher_pool_size);
    if (tmp != cipher_pool_size) {
        log.warn("%s: setting cipher_pool_size (%d) to %d (power of 2) for faster modulo operation", local_addr, cipher_pool_size, tmp);
        cipher_pool_size = tmp;
    }
    encoding_ciphers = new ArrayBlockingQueue<>(cipher_pool_size);
    decoding_ciphers = new ArrayBlockingQueue<>(cipher_pool_size);
    initSymCiphers(sym_algorithm, secret_key);
}

48. ArrayBlockingQueueTest#testContainsAll()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * containsAll(c) is true when c contains a subset of elements
     */
public void testContainsAll() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    ArrayBlockingQueue p = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertTrue(q.containsAll(p));
        assertFalse(p.containsAll(q));
        p.add(new Integer(i));
    }
    assertTrue(p.containsAll(q));
}

49. ArrayBlockingQueueTest#testContainsAll()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * containsAll(c) is true when c contains a subset of elements
     */
public void testContainsAll() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    ArrayBlockingQueue p = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertTrue(q.containsAll(p));
        assertFalse(p.containsAll(q));
        p.add(new Integer(i));
    }
    assertTrue(p.containsAll(q));
}

50. StreamingUDF#initialize()

Project: pig
Source File: StreamingUDF.java
View license
private void initialize() throws ExecException, IOException {
    inputQueue = new ArrayBlockingQueue<Tuple>(1);
    outputQueue = new ArrayBlockingQueue<Object>(2);
    soc = new ScriptingOutputCapturer(execType);
    startUdfController();
    createInputHandlers();
    setStreams();
    startThreads();
}

51. PostMessage#init()

Project: activemq-artemis
Source File: PostMessage.java
View license
public void init() throws Exception {
    pool = new ArrayBlockingQueue<>(poolSize);
    for (int i = 0; i < poolSize; i++) {
        addPooled();
    }
}

52. ApacheLogInputGenerator#setup()

View license
@Override
public void setup(OperatorContext arg0) {
    holdingBuffer = new ArrayBlockingQueue<String>(bufferSize);
    try {
        ipAddress = readLines(ipAddressFile);
        List<String> urlByteStatus = readLines(urlFile);
        referers = readLines(refererFile);
        agents = readLines(agentFile);
        //removing the first url if it starts with #
        if (urlByteStatus.get(0).startsWith("#")) {
            urlByteStatus.remove(0);
        }
        LOG.info("Number of IP Addresses: {}", ipAddress.size());
        LOG.info("Number of URLs: {}", urlByteStatus.size());
        LOG.info("Number of Referers: {}", referers.size());
        LOG.info("Number of User Agents: {}", agents.size());
        url = new ArrayList<String>();
        bytes = new ArrayList<Integer>();
        status = new ArrayList<Integer>();
        StringTokenizer token;
        for (String str : urlByteStatus) {
            token = new StringTokenizer(str, delimiter);
            url.add(token.nextToken().trim());
            bytes.add(Integer.parseInt(token.nextToken().trim()));
            status.add(Integer.parseInt(token.nextToken().trim()));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    random = new Random();
    ipAddressCount = ipAddress.size();
    agentsCount = agents.size();
    urlCount = url.size();
    refererCount = referers.size();
    sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");
}

53. AbstractElasticSearchOutputOperator#setup()

View license
/**
   * Initialize transient fields such as {@code tupleBatch}
   *
   * @see com.datatorrent.lib.db.AbstractStoreOutputOperator#setup(com.datatorrent.api.Context.OperatorContext)
   */
@Override
public void setup(OperatorContext context) {
    super.setup(context);
    tupleBatch = new ArrayBlockingQueue<T>(batchSize);
}

54. KafkaConsumer#create()

Project: apex-malhar
Source File: KafkaConsumer.java
View license
/**
   * This method is called in setup method of the operator
   */
public void create() {
    initBrokers();
    holdingBuffer = new ArrayBlockingQueue<KafkaMessage>(cacheSize);
}

55. KinesisConsumer#create()

Project: apex-malhar
Source File: KinesisConsumer.java
View license
/**
   * This method is called in setup method of the operator
   */
public void create() {
    holdingBuffer = new ArrayBlockingQueue<Pair<String, Record>>(bufferSize);
    boolean defaultSelect = (shardIds == null) || (shardIds.size() == 0);
    final List<Shard> pms = KinesisUtil.getInstance().getShardList(streamName);
    for (final Shard shId : pms) {
        if ((shardIds.contains(shId.getShardId()) || defaultSelect) && !closedShards.contains(shId)) {
            simpleConsumerThreads.add(shId);
        }
    }
}

56. AbstractMqttInputOperator#setup()

View license
@Override
public void setup(OperatorContext t1) {
    holdingBuffer = new ArrayBlockingQueue<Message>(bufferSize);
}

57. AbstractRabbitMQInputOperator#setup()

View license
@Override
public void setup(OperatorContext context) {
    this.operatorContextId = context.getId();
    holdingBuffer = new ArrayBlockingQueue<KeyValPair<Long, byte[]>>(bufferSize);
    this.windowDataManager.setup(context);
}

58. AbstractSolrOutputOperator#setup()

View license
@Override
public void setup(OperatorContext context) {
    docBuffer = new ArrayBlockingQueue<SolrInputDocument>(bufferSize);
    try {
        solrServerConnector.connect();
    } catch (Exception ex) {
        throw new RuntimeException("Unable to connect to Solr server", ex);
    }
}

59. SourceModule#setup()

Project: apex-malhar
Source File: SourceModule.java
View license
@Override
public void setup(OperatorContext context) {
    holdingBuffer = new ArrayBlockingQueue<byte[]>(1024 * 1024);
}

60. KafkaConsumerWrapper#create()

View license
/**
   * This method is called in setup method of Abstract Kafka Input Operator
   */
public void create(AbstractKafkaInputOperator ownerOperator) {
    holdingBuffer = new ArrayBlockingQueue<>(ownerOperator.getHoldingBufferSize());
    this.ownerOperator = ownerOperator;
    logger.info("Create consumer wrapper with holding buffer size: {} ", ownerOperator.getHoldingBufferSize());
    if (logger.isInfoEnabled()) {
        logger.info("Assignments are {} ", Joiner.on('\n').join(ownerOperator.assignment()));
    }
}

61. GdbDebuggerTest#beforeClass()

Project: che
Source File: GdbDebuggerTest.java
View license
@BeforeClass
public void beforeClass() throws Exception {
    file = GdbTest.class.getResource("/hello").getFile();
    sourceDirectory = Paths.get(GdbTest.class.getResource("/h.cpp").getFile());
    events = new ArrayBlockingQueue<>(10);
}

62. HttpClientSource#init()

Project: datacollector
Source File: HttpClientSource.java
View license
@Override
protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();
    errorRecordHandler = new DefaultErrorRecordHandler(getContext());
    conf.basic.init(getContext(), Groups.HTTP.name(), BASIC_CONFIG_PREFIX, issues);
    conf.dataFormatConfig.init(getContext(), conf.dataFormat, Groups.HTTP.name(), DATA_FORMAT_CONFIG_PREFIX, issues);
    conf.init(getContext(), Groups.HTTP.name(), "conf.", issues);
    conf.sslConfig.init(getContext(), Groups.SSL.name(), "conf.sslConfig.", issues);
    // Queue may not be empty at shutdown, but because we can't rewind,
    // the dropped entities are not recoverable anyway. In the case
    // that the pipeline is restarted we'll resume with any entities still enqueued.
    entityQueue = new ArrayBlockingQueue<>(2 * conf.basic.maxBatchSize);
    parserFactory = conf.dataFormatConfig.getParserFactory();
    httpConsumer = new HttpStreamConsumer(conf, getContext(), entityQueue);
    switch(conf.httpMode) {
        case STREAMING:
            createStreamingConsumer();
            break;
        case POLLING:
            createPollingConsumer();
            break;
        default:
            throw new IllegalStateException("Unrecognized httpMode " + conf.httpMode);
    }
    return issues;
}

63. TestRulesConfigLoader#setUp()

View license
@Before
public void setUp() {
    productionObserveRequests = new ArrayBlockingQueue<>(10, true);
    observer = new ProductionObserver(new Configuration(), null);
    observer.setObserveRequests(productionObserveRequests);
}

64. OmnitureSource#init()

Project: datacollector
Source File: OmnitureSource.java
View license
@Override
protected List<ConfigIssue> init() {
    List<ConfigIssue> errors = super.init();
    errorRecordHandler = new DefaultErrorRecordHandler(getContext());
    // TODO: SDC-552 - Omniture origin should be recoverable
    entityQueue = new ArrayBlockingQueue<>(2 * batchSize);
    parserFactory = new DataParserFactoryBuilder(getContext(), DataParserFormat.JSON).setMode(JsonMode.MULTIPLE_OBJECTS).setMaxDataLen(-1).build();
    switch(httpMode) {
        case POLLING:
            validateReportDescription(errors);
            httpConsumer = new OmniturePollingConsumer(resourceUrl, reportDescription, requestTimeoutMillis, username, sharedSecret, entityQueue, proxySettings);
            createPollingConsumer();
            break;
        default:
            throw new IllegalStateException("Unrecognized httpMode " + httpMode);
    }
    return errors;
}

65. TextExtractor#initialize()

Project: jackrabbit-oak
Source File: TextExtractor.java
View license
private synchronized void initialize() throws IOException {
    if (initialized) {
        return;
    }
    inputQueue = new ArrayBlockingQueue<WorkItem>(queueSize);
    tika = new TikaHelper(tikaConfig);
    initializeExecutorService();
    initialized = true;
}

66. NoBundler#init()

Project: JGroups
Source File: NoBundler.java
View license
public void init(TP transport) {
    this.transport = transport;
    log = transport.getLog();
    buf_pool = new ArrayBlockingQueue<>(pool_size);
    IntStream.rangeClosed(1, pool_size).forEach( ignored -> buf_pool.offer(new ByteArrayDataOutputStream(initial_buf_size)));
// transport.registerProbeHandler(send);
}

67. ArrayBlockingQueueTest#testConstructor7()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Queue contains all elements of collection used to initialize
     */
public void testConstructor7() {
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE; ++i) ints[i] = i;
    Collection<Integer> elements = Arrays.asList(ints);
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, elements);
    for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll());
}

68. ArrayBlockingQueueTest#testOffer()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Offer succeeds if not full; fails if full
     */
public void testOffer() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(1);
    assertTrue(q.offer(zero));
    assertFalse(q.offer(one));
}

69. ArrayBlockingQueueTest#testAdd()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * add succeeds if not full; throws ISE if full
     */
public void testAdd() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertTrue(q.add(new Integer(i)));
    }
    assertEquals(0, q.remainingCapacity());
    try {
        q.add(new Integer(SIZE));
        shouldThrow();
    } catch (IllegalStateException success) {
    }
}

70. ArrayBlockingQueueTest#testAddAllSelf()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * addAll(this) throws IAE
     */
public void testAddAllSelf() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    try {
        q.addAll(q);
        shouldThrow();
    } catch (IllegalArgumentException success) {
    }
}

71. ArrayBlockingQueueTest#testAddAll3()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * addAll of a collection with any null elements throws NPE after
     * possibly adding some elements
     */
public void testAddAll3() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE - 1; ++i) ints[i] = new Integer(i);
    try {
        q.addAll(Arrays.asList(ints));
        shouldThrow();
    } catch (NullPointerException success) {
    }
}

72. ArrayBlockingQueueTest#testAddAll4()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * addAll throws ISE if not enough room
     */
public void testAddAll4() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(1);
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE; ++i) ints[i] = new Integer(i);
    try {
        q.addAll(Arrays.asList(ints));
        shouldThrow();
    } catch (IllegalStateException success) {
    }
}

73. ArrayBlockingQueueTest#testAddAll5()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Queue contains all elements, in traversal order, of successful addAll
     */
public void testAddAll5() {
    Integer[] empty = new Integer[0];
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE; ++i) ints[i] = new Integer(i);
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    assertFalse(q.addAll(Arrays.asList(empty)));
    assertTrue(q.addAll(Arrays.asList(ints)));
    for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll());
}

74. ArrayBlockingQueueTest#testPut()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * all elements successfully put are contained
     */
public void testPut() throws InterruptedException {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        Integer x = new Integer(i);
        q.put(x);
        assertTrue(q.contains(x));
    }
    assertEquals(0, q.remainingCapacity());
}

75. ArrayBlockingQueueTest#testBlockingPut()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * put blocks interruptibly if full
     */
public void testBlockingPut() throws InterruptedException {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            for (int i = 0; i < SIZE; ++i) q.put(i);
            assertEquals(SIZE, q.size());
            assertEquals(0, q.remainingCapacity());
            Thread.currentThread().interrupt();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
            pleaseInterrupt.countDown();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
        }
    });
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
    assertEquals(SIZE, q.size());
    assertEquals(0, q.remainingCapacity());
}

76. ArrayBlockingQueueTest#testPutWithTake()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * put blocks interruptibly waiting for take when full
     */
public void testPutWithTake() throws InterruptedException {
    final int capacity = 2;
    final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
    final CountDownLatch pleaseTake = new CountDownLatch(1);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            for (int i = 0; i < capacity; i++) q.put(i);
            pleaseTake.countDown();
            q.put(86);
            pleaseInterrupt.countDown();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
        }
    });
    await(pleaseTake);
    assertEquals(0, q.remainingCapacity());
    assertEquals(0, q.take());
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
    assertEquals(0, q.remainingCapacity());
}

77. ArrayBlockingQueueTest#testTake()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * take retrieves elements in FIFO order
     */
public void testTake() throws InterruptedException {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.take());
    }
}

78. ArrayBlockingQueueTest#testBlockingTake()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Take removes existing elements until empty, then blocks interruptibly
     */
public void testBlockingTake() throws InterruptedException {
    final ArrayBlockingQueue q = populatedQueue(SIZE);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            for (int i = 0; i < SIZE; ++i) {
                assertEquals(i, q.take());
            }
            Thread.currentThread().interrupt();
            try {
                q.take();
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
            pleaseInterrupt.countDown();
            try {
                q.take();
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
        }
    });
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
}

79. ArrayBlockingQueueTest#testPoll()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * poll succeeds unless empty
     */
public void testPoll() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.poll());
    }
    assertNull(q.poll());
}

80. ArrayBlockingQueueTest#testTimedPoll0()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * timed poll with zero timeout succeeds when non-empty, else times out
     */
public void testTimedPoll0() throws InterruptedException {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.poll(0, MILLISECONDS));
    }
    assertNull(q.poll(0, MILLISECONDS));
    checkEmpty(q);
}

81. ArrayBlockingQueueTest#testPeek()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * peek returns next element, or null if empty
     */
public void testPeek() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.peek());
        assertEquals(i, q.poll());
        assertTrue(q.peek() == null || !q.peek().equals(i));
    }
    assertNull(q.peek());
}

82. ArrayBlockingQueueTest#testElement()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * element returns next element, or throws NSEE if empty
     */
public void testElement() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.element());
        assertEquals(i, q.poll());
    }
    try {
        q.element();
        shouldThrow();
    } catch (NoSuchElementException success) {
    }
}

83. ArrayBlockingQueueTest#testRemove()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * remove removes next element, or throws NSEE if empty
     */
public void testRemove() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.remove());
    }
    try {
        q.remove();
        shouldThrow();
    } catch (NoSuchElementException success) {
    }
}

84. ArrayBlockingQueueTest#testContains()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * contains(x) reports true when elements added but not yet removed
     */
public void testContains() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertTrue(q.contains(new Integer(i)));
        assertEquals(i, q.poll());
        assertFalse(q.contains(new Integer(i)));
    }
}

85. ArrayBlockingQueueTest#testToArray1_BadArg()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * toArray(incompatible array type) throws ArrayStoreException
     */
public void testToArray1_BadArg() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    try {
        q.toArray(new String[10]);
        shouldThrow();
    } catch (ArrayStoreException success) {
    }
}

86. ArrayBlockingQueueTest#testToString()

Project: mapdb
Source File: ArrayBlockingQueueTest.java
View license
/**
     * toString contains toStrings of elements
     */
public void testToString() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    String s = q.toString();
    for (int i = 0; i < SIZE; ++i) {
        assertTrue(s.contains(String.valueOf(i)));
    }
}

87. ZWaveWakeUpCommandClass#readResolve()

View license
/**
     * Resolves uninitialized fields after XML Deserialization.
     *
     * @return The current {@link ZWaveWakeUpCommandClass} instance.
     */
private Object readResolve() {
    wakeUpQueue = new ArrayBlockingQueue<SerialMessage>(MAX_BUFFFER_SIZE, true);
    timer = new Timer();
    return this;
}

88. ZWaveWakeUpCommandClass#readResolve()

View license
/**
     * Resolves uninitialized fields after XML Deserialization.
     *
     * @return The current {@link ZWaveWakeUpCommandClass} instance.
     */
private Object readResolve() {
    wakeUpQueue = new ArrayBlockingQueue<SerialMessage>(MAX_BUFFFER_SIZE, true);
    timer = new Timer();
    return this;
}

89. DrainToFails#testUnbounded()

Project: openjdk
Source File: DrainToFails.java
View license
void testUnbounded(final BlockingQueue q) throws Throwable {
    System.err.println(q.getClass().getSimpleName());
    for (int i = 0; i < CAPACITY; i++) q.add(i);
    ArrayBlockingQueue q2 = new ArrayBlockingQueue(SMALL);
    try {
        q.drainTo(q2, 7);
        fail("should throw");
    } catch (IllegalStateException success) {
        assertContentsInOrder(q2, 0, 1);
        q2.clear();
        equal(q.size(), CAPACITY - SMALL);
        equal(SMALL, q.peek());
    }
    try {
        q.drainTo(q2);
        fail("should throw");
    } catch (IllegalStateException success) {
        assertContentsInOrder(q2, 2, 3);
        equal(q.size(), CAPACITY - 2 * SMALL);
        for (int i = 2 * SMALL; i < CAPACITY; i++) equal(i, q.poll());
        equal(0, q.size());
    }
}

90. DrainToFails#testBounded()

Project: openjdk
Source File: DrainToFails.java
View license
void testBounded(final BlockingQueue q) throws Throwable {
    System.err.println(q.getClass().getSimpleName());
    for (int i = 0; i < CAPACITY; i++) q.add(i);
    List<Thread> putters = new ArrayList<Thread>();
    for (int i = 0; i < 4; i++) {
        Thread putter = new Thread(putter(q, 42 + i));
        putters.add(putter);
        putter.setDaemon(true);
        putter.start();
    }
    ArrayBlockingQueue q2 = new ArrayBlockingQueue(SMALL);
    try {
        q.drainTo(q2, 7);
        fail("should throw");
    } catch (IllegalStateException success) {
        while (q.size() < CAPACITY) Thread.yield();
        assertContentsInOrder(q2, 0, 1);
        q2.clear();
    }
    try {
        q.drainTo(q2);
        fail("should throw");
    } catch (IllegalStateException success) {
        for (Thread putter : putters) {
            putter.join(2000L);
            check(!putter.isAlive());
        }
        assertContentsInOrder(q2, 2, 3);
        for (int i = 2 * SMALL; i < CAPACITY; i++) equal(i, q.poll());
        equal(4, q.size());
        check(q.contains(42));
        check(q.contains(43));
        check(q.contains(44));
        check(q.contains(45));
    }
}

91. ArrayBlockingQueueTest#testConstructor7()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Queue contains all elements of collection used to initialize
     */
public void testConstructor7() {
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE; ++i) ints[i] = i;
    Collection<Integer> elements = Arrays.asList(ints);
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, elements);
    for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll());
}

92. ArrayBlockingQueueTest#testOffer()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Offer succeeds if not full; fails if full
     */
public void testOffer() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(1);
    assertTrue(q.offer(zero));
    assertFalse(q.offer(one));
}

93. ArrayBlockingQueueTest#testAdd()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * add succeeds if not full; throws ISE if full
     */
public void testAdd() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertTrue(q.add(new Integer(i)));
    }
    assertEquals(0, q.remainingCapacity());
    try {
        q.add(new Integer(SIZE));
        shouldThrow();
    } catch (IllegalStateException success) {
    }
}

94. ArrayBlockingQueueTest#testAddAllSelf()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * addAll(this) throws IAE
     */
public void testAddAllSelf() {
    ArrayBlockingQueue q = populatedQueue(SIZE);
    try {
        q.addAll(q);
        shouldThrow();
    } catch (IllegalArgumentException success) {
    }
}

95. ArrayBlockingQueueTest#testAddAll3()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * addAll of a collection with any null elements throws NPE after
     * possibly adding some elements
     */
public void testAddAll3() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE - 1; ++i) ints[i] = new Integer(i);
    try {
        q.addAll(Arrays.asList(ints));
        shouldThrow();
    } catch (NullPointerException success) {
    }
}

96. ArrayBlockingQueueTest#testAddAll4()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * addAll throws ISE if not enough room
     */
public void testAddAll4() {
    ArrayBlockingQueue q = new ArrayBlockingQueue(1);
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE; ++i) ints[i] = new Integer(i);
    try {
        q.addAll(Arrays.asList(ints));
        shouldThrow();
    } catch (IllegalStateException success) {
    }
}

97. ArrayBlockingQueueTest#testAddAll5()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * Queue contains all elements, in traversal order, of successful addAll
     */
public void testAddAll5() {
    Integer[] empty = new Integer[0];
    Integer[] ints = new Integer[SIZE];
    for (int i = 0; i < SIZE; ++i) ints[i] = new Integer(i);
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    assertFalse(q.addAll(Arrays.asList(empty)));
    assertTrue(q.addAll(Arrays.asList(ints)));
    for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll());
}

98. ArrayBlockingQueueTest#testPut()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * all elements successfully put are contained
     */
public void testPut() throws InterruptedException {
    ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        Integer x = new Integer(i);
        q.put(x);
        assertTrue(q.contains(x));
    }
    assertEquals(0, q.remainingCapacity());
}

99. ArrayBlockingQueueTest#testBlockingPut()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * put blocks interruptibly if full
     */
public void testBlockingPut() throws InterruptedException {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            for (int i = 0; i < SIZE; ++i) q.put(i);
            assertEquals(SIZE, q.size());
            assertEquals(0, q.remainingCapacity());
            Thread.currentThread().interrupt();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
            pleaseInterrupt.countDown();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
        }
    });
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
    assertEquals(SIZE, q.size());
    assertEquals(0, q.remainingCapacity());
}

100. ArrayBlockingQueueTest#testPutWithTake()

Project: openjdk
Source File: ArrayBlockingQueueTest.java
View license
/**
     * put blocks interruptibly waiting for take when full
     */
public void testPutWithTake() throws InterruptedException {
    final int capacity = 2;
    final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
    final CountDownLatch pleaseTake = new CountDownLatch(1);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            for (int i = 0; i < capacity; i++) q.put(i);
            pleaseTake.countDown();
            q.put(86);
            pleaseInterrupt.countDown();
            try {
                q.put(99);
                shouldThrow();
            } catch (InterruptedException success) {
            }
            assertFalse(Thread.interrupted());
        }
    });
    await(pleaseTake);
    assertEquals(0, q.remainingCapacity());
    assertEquals(0, q.take());
    await(pleaseInterrupt);
    assertThreadStaysAlive(t);
    t.interrupt();
    awaitTermination(t);
    assertEquals(0, q.remainingCapacity());
}