Example usage for java.util.concurrent ArrayBlockingQueue ArrayBlockingQueue

List of usage examples for java.util.concurrent ArrayBlockingQueue ArrayBlockingQueue

Introduction

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

Prototype

public ArrayBlockingQueue(int capacity) 

Source Link

Document

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.

Usage

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

/**
 * Test if a {@link JackVaderFilter} 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 w w w.  ja va 2  s  .  c o m
 * 
 * @throws InterruptedException
 */
@Test
public void testFaceOverlayFilter() throws InterruptedException {
    PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_POINTER_DETECTOR).build();
    player.connect(overlayFilter);

    final BlockingQueue<EndOfStreamEvent> events = new ArrayBlockingQueue<EndOfStreamEvent>(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            events.add(event);
        }
    });

    player.play();

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

    player.stop();
    player.release();
}

From source file:ubic.gemma.core.loader.association.NCBIGene2GOAssociationLoader.java

public void load(final InputStream inputStream) {
    final BlockingQueue<Gene2GOAssociation> queue = new ArrayBlockingQueue<>(
            NCBIGene2GOAssociationLoader.QUEUE_SIZE);
    final SecurityContext context = SecurityContextHolder.getContext();
    final Authentication authentication = context.getAuthentication();

    Thread loadThread = new Thread(new Runnable() {
        @Override/*from  www . ja  va 2s .  c  om*/
        public void run() {
            NCBIGene2GOAssociationLoader.log.info("Starting loading");
            SecurityContextHolder.setContext(context);
            NCBIGene2GOAssociationLoader.this.load(queue);
        }
    });

    loadThread.start();

    Thread parseThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // NCBIGene2GOAssociationParser parser = new NCBIGene2GOAssociationParser();
                SecurityContextHolder.getContext().setAuthentication(authentication);
                parser.parse(inputStream, queue);
                NCBIGene2GOAssociationLoader.this.setCount(parser.getCount());
            } catch (IOException e) {
                NCBIGene2GOAssociationLoader.log.error(e, e);
                throw new RuntimeException(e);
            }
            NCBIGene2GOAssociationLoader.log.info("Done parsing");
            producerDone.set(true);
        }
    });

    parseThread.start();

    while (!this.isProducerDone() || !this.isConsumerDone()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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

@Test
public void testEventEndOfStream() throws InterruptedException {
    final BlockingQueue<EndOfStreamEvent> events = new ArrayBlockingQueue<EndOfStreamEvent>(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override/*from w w  w.j  a va 2  s.c  o  m*/
        public void onEvent(EndOfStreamEvent event) {
            events.add(event);
        }
    });

    player.play();

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

From source file:org.apache.hadoop.raid.JRSEncoder.java

public JRSEncoder(Configuration conf, int stripeSize, int paritySize) {
    super(conf, stripeSize, paritySize);

    threadNum = conf.getInt("hdfs.raid.encoder.threadnum", 2);

    this.q = new ArrayBlockingQueue[threadNum];
    for (int i = 0; i < threadNum; i++)
        q[i] = new ArrayBlockingQueue<ByteBuffer>(1024);

    this.p = new ArrayBlockingQueue[threadNum];
    for (int i = 0; i < threadNum; i++)
        p[i] = new ArrayBlockingQueue<Integer>(100);

    this.fq = new ArrayBlockingQueue[threadNum];
    for (int i = 0; i < threadNum; i++)
        fq[i] = new ArrayBlockingQueue<byte[][]>(2);

    //encode thread
    JRSMigrationEncoder[] encoder = new JRSMigrationEncoder[threadNum];
    Thread[] es = new Thread[threadNum];
    for (int i = 0; i < threadNum; i++) {
        encoder[i] = new JRSMigrationEncoder(i);
        es[i] = new Thread(encoder[i]);
        es[i].start();//from   w w  w  . ja v  a 2  s  .c  o m
    }

    LOG.info("JRSEncoder 21/10/12");
}

From source file:org.eobjects.analyzer.result.AnalyzerResultFutureTest.java

public void testMultiThreadedListenerScenario() throws Exception {
    final int threadCount = 10;

    final Thread[] threads = new Thread[threadCount];
    @SuppressWarnings({ "unchecked" })
    final Listener<NumberResult>[] listeners = new Listener[threadCount];
    final Queue<Object> resultQueue = new ArrayBlockingQueue<>(threadCount);

    for (int i = 0; i < listeners.length; i++) {
        listeners[i] = new Listener<NumberResult>() {
            @Override/*from   w  ww .  jav a  2s  . co  m*/
            public void onSuccess(NumberResult result) {
                resultQueue.add(result);
            }

            @Override
            public void onError(RuntimeException error) {
                resultQueue.add(error);
            }
        };
    }

    final Ref<NumberResult> resultRef = new LazyRef<NumberResult>() {
        @Override
        protected NumberResult fetch() throws Throwable {
            long randomSleepTime = (long) (1000 * Math.random());
            Thread.sleep(randomSleepTime);
            return new NumberResult(43);
        }
    };

    final AnalyzerResultFuture<NumberResult> future = new AnalyzerResultFuture<>("foo", resultRef);

    for (int i = 0; i < threads.length; i++) {
        final Listener<NumberResult> listener = listeners[i];
        threads[i] = new Thread() {
            @Override
            public void run() {
                future.addListener(listener);
            }
        };
    }

    final int halfOfTheThreads = threads.length / 2;
    for (int i = 0; i < halfOfTheThreads; i++) {
        threads[i].start();
    }
    for (int i = 0; i < halfOfTheThreads; i++) {
        threads[i].join();
    }

    future.get();

    assertEquals("[43, 43, 43, 43, 43]", resultQueue.toString());
    assertEquals(halfOfTheThreads, resultQueue.size());

    for (int i = halfOfTheThreads; i < threads.length; i++) {
        threads[i].start();
    }
    for (int i = halfOfTheThreads; i < threads.length; i++) {
        threads[i].join();
    }

    assertEquals("[43, 43, 43, 43, 43, 43, 43, 43, 43, 43]", resultQueue.toString());
    assertEquals(threads.length, resultQueue.size());
}

From source file:broadwick.montecarlo.MonteCarlo.java

/**
 * Run the Monte Carlo simulations. Two threads (a producer and consumer) are created to asynchronously run the
 * simulations (the producer) and to handle the results from each simulation as they are calculated (the consumer).
 * The producer thread uses an execution pool to manage running each simulation and places the results on a queue
 * which is monitored by a consumer thread to calculate the posterior distributions for the Monte Carlo run.
 *///ww w .  ja  v  a  2  s. c  o m
public final void run() {

    final ArrayBlockingQueue<MonteCarloResults> queue = new ArrayBlockingQueue<>(numSimulations + 1);

    //Creating Producer and Consumer Thread
    if (log.isTraceEnabled()) {
        log.trace("Creating Monte Carlo producer and consumer");
    }
    final Thread producer = new Thread(new Producer(queue, simulation, numSimulations));
    final Thread consumer = new Thread(new Consumer(queue, resultsConsumer));

    producer.start();
    consumer.start();

    try {
        producer.join();
        consumer.join();
    } catch (Exception e) {
        log.error("Error joining Monte Carlo results {}", Throwables.getStackTraceAsString(e));
    }
}

From source file:org.opencb.cellbase.core.variant_annotation.VariantAnnotatorRunner.java

public VariantAnnotatorRunner(Path inputFile, Path outputFile, CellBaseClient cellBaseClient, int numThreads,
        int batchSize) {
    this.inputFile = inputFile;
    this.outputFile = outputFile;
    this.variantQueue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
    this.variantAnnotationQueue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
    this.cellBaseClient = cellBaseClient;
    this.numThreads = numThreads;
    this.batchSize = batchSize;

    logger = LoggerFactory.getLogger(this.getClass());
}

From source file:scheduler.ServerThread.java

@SuppressWarnings("unchecked")
public void run() {

    try {// w  ww .j a v  a  2s  .  co m
        InputStream inStream = server.getInputStream();
        OutputStream outStream = server.getOutputStream();

        PrintWriter out = new PrintWriter(outStream, true);
        BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

        if (workerType.equals("rw")) {
            jobQ = new SQSService("JobQueue");
            //Use client ip as the name of the response queue
            String resQName = server.getInetAddress().toString().substring(1).replaceAll("[^0-9]", "-");
            resQ = new SQSService(resQName);

            //Send tasks
            remoteBatchSend(in);

            //Get results
            remoteBatchReceive(out);

        } else {
            localJobQ = new ArrayBlockingQueue<String>(1024 * 1024);
            localRespQ = new ArrayBlockingQueue<String>(1024 * 1024);
            //Local worker
            localSend(in);
            localReceive(out);

        }

        server.close();

    } catch (IOException | ParseException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testNoPendingTask() throws Exception {
    // Assuming there is no task in the queue in the test.
    PowerMockito.when(taskQueue.dequeueTask(anyString())).thenReturn(null);
    Semaphore idleWorkersSemaphore = new Semaphore(1);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, taskQueue);
    TaskDispatcher dispatcher = new TaskDispatcher(1, idleWorkersSemaphore, workerPool, taskQueue);
    dispatcher.start();//  w w  w .  ja  v  a 2  s . c o m
    Thread.sleep(1000);
    Assert.assertEquals(1, idleWorkersSemaphore.availablePermits());
    Thread.sleep(1000);
    Assert.assertEquals(1, idleWorkersSemaphore.availablePermits());
    dispatcher.stop();
}

From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    System.out.println("FeedServlet Started");

    int feedProcessorThreads = ConstellioSpringUtils.getFeedProcessorThreads();
    threadPoolExecutor = new ThreadPoolExecutor(feedProcessorThreads, feedProcessorThreads, 5, TimeUnit.MINUTES,
            new ArrayBlockingQueue<Runnable>(feedProcessorThreads + 1),
            new ThreadPoolExecutor.CallerRunsPolicy());
}