Example usage for java.util.concurrent BlockingQueue poll

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

Introduction

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

Prototype

E poll(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.

Usage

From source file:com.kurento.kmf.media.PlateDetectorFilterTest.java

@Test
public void testEventPlateDetected() throws InterruptedException {
    final BlockingQueue<PlateDetectedEvent> events = new ArrayBlockingQueue<PlateDetectedEvent>(1);
    detector.addPlateDetectedListener(new MediaEventListener<PlateDetectedEvent>() {

        @Override//from w  ww . j  av  a  2  s. c  o  m
        public void onEvent(PlateDetectedEvent event) {
            events.add(event);
        }
    });
    player.connect(detector);
    player.play();

    PlateDetectedEvent event = events.poll(7, SECONDS);
    Assert.assertNotNull(event);
}

From source file:org.apache.camel.component.seda.SedaConsumer.java

public void run() {
    BlockingQueue<Exchange> queue = endpoint.getQueue();
    // loop while we are allowed, or if we are stopping loop until the queue is empty
    while (queue != null && (isRunAllowed())) {
        Exchange exchange = null;//from   w ww  . j  a  v  a 2  s  . c om
        try {
            exchange = queue.poll(1000, TimeUnit.MILLISECONDS);
            if (exchange != null) {
                try {
                    sendToConsumers(exchange);

                    // log exception if an exception occurred and was not handled
                    if (exchange.getException() != null) {
                        getExceptionHandler().handleException("Error processing exchange", exchange,
                                exchange.getException());
                    }
                } catch (Exception e) {
                    getExceptionHandler().handleException("Error processing exchange", exchange, e);
                }
            } else if (shutdownPending && queue.isEmpty()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace(
                            "Shutdown is pending, so this consumer thread is breaking out because the task queue is empty.");
                }
                // we want to shutdown so break out if there queue is empty
                break;
            }
        } catch (InterruptedException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Sleep interrupted, are we stopping? " + (isStopping() || isStopped()));
            }
            continue;
        } catch (Throwable e) {
            if (exchange != null) {
                getExceptionHandler().handleException("Error processing exchange", exchange, e);
            } else {
                getExceptionHandler().handleException(e);
            }
        }
    }

    latch.countDown();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Ending this polling consumer thread, there are still " + latch.getCount()
                + " consumer threads left.");
    }
}

From source file:com.kurento.kmf.media.PointerDetectorFilterTest.java

/**
 * Test if a {@link PointerDetectorFilter} can be created in the KMS. The
 * filter is pipelined with a {@link PlayerEndpoint}, which feeds video to
 * the filter. This test depends on the correct behaviour of the player and
 * its events./*from   ww  w. ja va 2s  .co  m*/
 * 
 * @throws InterruptedException
 */
@Test
public void testPointerDetectorFilter() throws InterruptedException {
    player.connect(filter);

    filter.addWindow(new PointerDetectorWindowMediaParam("goal", 50, 50, 150, 150));
    final BlockingQueue<WindowInEvent> events = new ArrayBlockingQueue<WindowInEvent>(1);
    filter.addWindowInListener(new MediaEventListener<WindowInEvent>() {
        @Override
        public void onEvent(WindowInEvent event) {
            events.add(event);
        }
    });

    player.play();

    Assert.assertNotNull(events.poll(20, SECONDS));

    player.stop();
}

From source file:com.kurento.kmf.media.AbstractAsyncBaseTest.java

@Before
public void abstractSetup() throws InterruptedException {
    final BlockingQueue<MediaPipeline> events = new ArrayBlockingQueue<MediaPipeline>(1);
    pipelineFactory.create(new Continuation<MediaPipeline>() {
        @Override//  ww w. j  a  v  a2 s.  co m
        public void onSuccess(MediaPipeline result) {
            events.add(result);
        }

        @Override
        public void onError(Throwable cause) {
            throw new KurentoMediaFrameworkException(cause);
        }
    });
    pipeline = events.poll(500, MILLISECONDS);

    if (pipeline == null) {
        Assert.fail();
    }
}

From source file:com.kurento.kmf.media.HttpGetEndpointAsyncTest.java

/**
 * Checks that the getUrl method does not return an empty string
 * //from w ww  .jav a 2 s . c  om
 * @throws InterruptedException
 */
@Test
public void testMethodGetUrl() throws InterruptedException {
    final BlockingQueue<String> events = new ArrayBlockingQueue<String>(1);
    httpEp.getUrl(new Continuation<String>() {

        @Override
        public void onSuccess(String result) {
            events.add(result);
        }

        @Override
        public void onError(Throwable cause) {
            throw new KurentoMediaFrameworkException(cause);
        }
    });

    String url = events.poll(500, MILLISECONDS);
    Assert.assertTrue(!(url == null || url.isEmpty()));
}

From source file:com.nridge.connector.fs.con_fs.core.RunTransformFS.java

/**
 * When an object implementing interface <code>Runnable</code> is used
 * to create a thread, starting the thread causes the object's
 * <code>run</code> method to be called in that separately executing
 * thread./*  www.  j ava 2 s.  c  o  m*/
 * 
 * The general contract of the method <code>run</code> is that it may
 * take any action whatsoever.
 *
 * @see Thread#run()
 */
@Override
public void run() {
    DocumentXML documentXML;
    Document srcDoc, dstDoc;
    String docId, queueItem, srcPathFileName;
    Logger appLogger = mAppMgr.getLogger(this, "run");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Pipeline pipeline = new Pipeline(mAppMgr, Constants.CFG_PROPERTY_PREFIX);

    BlockingQueue extractQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_EXTRACT_NAME);
    BlockingQueue transformQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_TRANSFORM_NAME);

    long queueWaitTimeout = mAppMgr.getLong(Constants.CFG_PROPERTY_PREFIX + ".queue.wait_timeout",
            Constants.QUEUE_POLL_TIMEOUT_DEFAULT);
    do {
        try {
            queueItem = (String) extractQueue.poll(queueWaitTimeout, TimeUnit.SECONDS);
            if (mCrawlQueue.isQueueItemDocument(queueItem)) {
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                docId = Connector.docIdFromQueueItem(queueItem);

                appLogger.debug(String.format("Extract Queue Item: %s", docId));
                srcPathFileName = mCrawlQueue.docPathFileName(Connector.QUEUE_EXTRACT_NAME, docId);
                try {
                    documentXML = new DocumentXML();
                    documentXML.load(srcPathFileName);
                    srcDoc = documentXML.getDocument();

                    dstDoc = pipeline.execute(srcDoc);

                    mCrawlQueue.transition(Connector.QUEUE_EXTRACT_NAME, Connector.QUEUE_TRANSFORM_NAME, dstDoc,
                            docId);
                    stopWatch.stop();
                    queueItem = Connector.queueItemIdPhaseTime(queueItem, Connector.PHASE_TRANSFORM,
                            stopWatch.getTime());
                    try {
                        // If queue is full, this thread may block.
                        transformQueue.put(queueItem);
                    } catch (InterruptedException e) {
                        // Restore the interrupted status so parent can handle (if it wants to).
                        Thread.currentThread().interrupt();
                    }
                } catch (Exception e) {
                    String msgStr = String.format("%s: %s", docId, e.getMessage());
                    appLogger.error(msgStr, e);
                    MailManager mailManager = (MailManager) mAppMgr.getProperty(Connector.PROPERTY_MAIL_NAME);
                    mailManager.addMessage(Connector.PHASE_TRANSFORM, Connector.STATUS_MAIL_ERROR, msgStr,
                            Constants.MAIL_DETAIL_MESSAGE);
                }
            }
        } catch (InterruptedException e) {
            queueItem = StringUtils.EMPTY;
        }
    } while (!mCrawlQueue.isPhaseComplete(Connector.PHASE_EXTRACT, queueItem));

    // Forward the marker queue item to the next queue.

    if (mCrawlQueue.isQueueItemMarker(queueItem)) {
        try {
            // If queue is full, this thread may block.
            transformQueue.put(queueItem);
        } catch (InterruptedException e) {
            // Restore the interrupted status so parent can handle (if it wants to).
            Thread.currentThread().interrupt();
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.all.backend.web.services.LocalPushService.java

@SuppressWarnings("unchecked")
@Override//www.  j  a  va  2s .c  o m
public AllMessage<?> pullMessage(ContactInfo contact) {
    long id = contact.getId();
    BlockingQueue<AllMessage<?>> queue;
    synchronized (messages) {
        queue = messages.get(id);
        if (queue == null) {
            queue = new LinkedBlockingQueue<AllMessage<?>>();
            messages.put(id, queue);
        }
    }
    AllMessage<?> poll = null;
    try {
        poll = queue.poll(1, TimeUnit.MINUTES);
    } catch (Exception e) {
        log.error(e, e);
    }
    if (poll == null) {
        synchronized (messages) {
            if (queue.isEmpty()) {
                messages.remove(id);
            }
        }
    }
    return poll;
}

From source file:com.nridge.connector.fs.con_fs.core.RunPublishFS.java

/**
 * When an object implementing interface <code>Runnable</code> is used
 * to create a thread, starting the thread causes the object's
 * <code>run</code> method to be called in that separately executing
 * thread.//from   ww  w .j  a  v a 2  s.  c  o m
 * 
 * The general contract of the method <code>run</code> is that it may
 * take any action whatsoever.
 *
 * @see Thread#run()
 */
@Override
public void run() {
    Document conDoc;
    DocumentXML documentXML;
    String docId, queueItem, srcPathFileName;
    Logger appLogger = mAppMgr.getLogger(this, "run");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    boolean isPublisherInitialized = true;
    DataBag schemaBag = (DataBag) mAppMgr.getProperty(Connector.PROPERTY_SCHEMA_NAME);
    Publishers indexPublishers = new Publishers(mAppMgr, mCrawlQueue, Constants.CFG_PROPERTY_PREFIX);
    try {
        indexPublishers.initialize(schemaBag);
    } catch (NSException e) {
        isPublisherInitialized = false;
        appLogger.error("Publisher initialization: " + e.getMessage());
    }

    if (isPublisherInitialized) {
        BlockingQueue transformQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_TRANSFORM_NAME);
        BlockingQueue publishQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_PUBLISH_NAME);

        long queueWaitTimeout = mAppMgr.getLong(Constants.CFG_PROPERTY_PREFIX + ".queue.wait_timeout",
                Constants.QUEUE_POLL_TIMEOUT_DEFAULT);
        do {
            try {
                queueItem = (String) transformQueue.poll(queueWaitTimeout, TimeUnit.SECONDS);
                if (mCrawlQueue.isQueueItemDocument(queueItem)) {
                    StopWatch stopWatch = new StopWatch();
                    stopWatch.start();

                    docId = Connector.docIdFromQueueItem(queueItem);

                    appLogger.debug(String.format("Transform Queue Item: %s", docId));
                    srcPathFileName = mCrawlQueue.docPathFileName(Connector.QUEUE_TRANSFORM_NAME, docId);
                    try {
                        documentXML = new DocumentXML();
                        documentXML.load(srcPathFileName);
                        conDoc = documentXML.getDocument();

                        indexPublishers.send(conDoc);

                        File srcFile = new File(srcPathFileName);
                        if (!srcFile.delete())
                            appLogger.warn(String.format("%s: Unable to delete.", srcPathFileName));

                        stopWatch.stop();
                        queueItem = Connector.queueItemIdPhaseTime(queueItem, Connector.PHASE_PUBLISH,
                                stopWatch.getTime());
                        try {
                            // If queue is full, this thread may block.
                            publishQueue.put(queueItem);
                        } catch (InterruptedException e) {
                            // Restore the interrupted status so parent can handle (if it wants to).
                            Thread.currentThread().interrupt();
                        }
                    } catch (Exception e) {
                        String msgStr = String.format("%s: %s", docId, e.getMessage());
                        appLogger.error(msgStr, e);
                        MailManager mailManager = (MailManager) mAppMgr
                                .getProperty(Connector.PROPERTY_MAIL_NAME);
                        mailManager.addMessage(Connector.PHASE_PUBLISH, Connector.STATUS_MAIL_ERROR, msgStr,
                                Constants.MAIL_DETAIL_MESSAGE);
                    }
                }
            } catch (InterruptedException e) {
                queueItem = StringUtils.EMPTY;
            }
        } while (!mCrawlQueue.isPhaseComplete(Connector.PHASE_TRANSFORM, queueItem));

        // Forward the marker queue item to the next queue.

        if (mCrawlQueue.isQueueItemMarker(queueItem)) {
            try {
                // If queue is full, this thread may block.
                publishQueue.put(queueItem);
            } catch (InterruptedException e) {
                // Restore the interrupted status so parent can handle (if it wants to).
                Thread.currentThread().interrupt();
            }
        }

        // Now we can shutdown our search indexer publisher.

        try {
            indexPublishers.shutdown();
        } catch (NSException e) {
            appLogger.error("Publisher shutdown: " + e.getMessage());
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:siddur.solidtrust.azure.AzureCarController.java

private ExecutorService consume(final BlockingQueue<List<AzureCar>> queue, int count) {
    Runnable consumer = new Runnable() {
        @Override/*from   ww  w  . j a v a2  s  .c  o m*/
        public void run() {
            try {
                while (running) {
                    List<AzureCar> batch = queue.poll(100, TimeUnit.SECONDS);
                    if (batch != null) {
                        persister.saveBatch(batch);
                    }
                }
            } catch (InterruptedException e) {
                log4j.info(e.getMessage(), e);
            }
        }
    };

    ExecutorService pool = Executors.newFixedThreadPool(count);
    for (int i = 0; i < count; i++) {
        pool.execute(consumer);
    }
    return pool;
}

From source file:org.apache.s4.core.classloader.TestClassLoader.java

@Test
public void testInitialDeploymentFromFileSystem() throws Exception {

    File producerS4R = new File(producerS4rDir, "testApp-0.0.0-SNAPSHOT.s4r");
    String uriProducer = producerS4R.toURI().toString();

    initializeS4Node();/*www. j a  va  2s .c  o  m*/

    final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    zkClient.subscribeDataChanges("/s4/classLoader", new IZkDataListener() {

        @Override
        public void handleDataDeleted(String dataPath) throws Exception {
        }

        @Override
        public void handleDataChange(String dataPath, Object data) throws Exception {
            queue.put(data);
        }
    });
    DeploymentUtils.initAppConfig(new AppConfig.Builder().appURI(uriProducer).build(), PRODUCER_CLUSTER, true,
            "localhost:2181");

    Object classLoaderRecord = queue.poll(20, TimeUnit.SECONDS);
    assertTrue("Stored record has unexpected type", classLoaderRecord instanceof ZNRecord);
    ZNRecord record = (ZNRecord) classLoaderRecord;

    assertEquals("Unexpected classloader runs the app init()", S4RLoader.class.getName(), record.getId());
}