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.HttpPostEndpointTest.java

/**
 * Test for {@link MediaSessionStartedEvent}
 * //from  www.jav  a 2  s. c  o m
 * @throws InterruptedException
 */
@Test
public void testEventMediaSessionStarted() throws InterruptedException {
    final PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    HttpPostEndpoint httpEP = pipeline.newHttpPostEndpoint().build();
    player.connect(httpEP);

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

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

    httpEP.addMediaSessionStartedListener(new MediaEventListener<MediaSessionStartedEvent>() {

        @Override
        public void onEvent(MediaSessionStartedEvent event) {
            player.play();
        }
    });

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        // This should trigger MediaSessionStartedEvent
        httpclient.execute(new HttpGet(httpEP.getUrl()));
    } catch (ClientProtocolException e) {
        throw new KurentoMediaFrameworkException();
    } catch (IOException e) {
        throw new KurentoMediaFrameworkException();
    }

    Assert.assertNotNull(eosEvents.poll(7, SECONDS));

    httpEP.release();
    player.release();
}

From source file:org.apache.http.impl.client.cache.AsynchronousAsyncValidator.java

/**
 * Create AsynchronousValidator which will make revalidation requests using
 * the supplied {@link CachingHttpAsyncClient}, and a {@link ThreadPoolExecutor}
 * generated according to the thread pool settings provided in the given
 * {@link CacheConfig}.//  ww  w.  j  ava 2s  .  co  m
 *
 * @param cachingClient
 *            used to execute asynchronous requests
 * @param config
 *            specifies thread pool settings. See
 *            {@link CacheConfig#getAsynchronousWorkersMax()},
 *            {@link CacheConfig#getAsynchronousWorkersCore()},
 *            {@link CacheConfig#getAsynchronousWorkerIdleLifetimeSecs()},
 *            and {@link CacheConfig#getRevalidationQueueSize()}.
 */
public AsynchronousAsyncValidator(final CachingHttpAsyncClient cachingClient, final CacheConfig config) {
    this(cachingClient,
            new ThreadPoolExecutor(config.getAsynchronousWorkersCore(), config.getAsynchronousWorkersMax(),
                    config.getAsynchronousWorkerIdleLifetimeSecs(), TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(config.getRevalidationQueueSize())));
}

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

@Test
public void testAssignSameClusterConflict() throws Exception {
    Semaphore idleWorkersSemaphore = new Semaphore(0);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, new TaskQueue() {
    });/*from   w  w  w. ja v a  2  s  . com*/
    Task task = getSleepIncrementTask();
    workerPool.assignTask(task);
    Thread.sleep(2000);
    Assert.assertEquals(1, SleepIncrementTask.executionCounter.intValue());
    workerPool.assignTask(task);
    Assert.assertEquals(1, idleWorkersSemaphore.availablePermits());
    Thread.sleep(100);
    Assert.assertEquals(1, SleepIncrementTask.executionCounter.intValue());
    Thread.sleep(1000);
}

From source file:uk.co.modularaudio.service.jobexecutor.impl.JobExecutorServiceImpl.java

@Override
public void init() throws ComponentConfigurationException {
    if (configurationService == null) {
        throw new ComponentConfigurationException("Service missing dependencies. Check configuration");
    }//w  w  w .  j a v  a  2 s .  c  o m

    final Map<String, String> errors = new HashMap<String, String>();

    poolSize = ConfigurationServiceHelper.checkForIntKey(configurationService, CONFIG_KEY_POOL_SIZE, errors);
    maximumPoolSize = ConfigurationServiceHelper.checkForIntKey(configurationService,
            CONFIG_KEY_MAXIMUM_POOL_SIZE, errors);
    jobQueueSize = ConfigurationServiceHelper.checkForIntKey(configurationService, CONFIG_KEY_JOB_QUEUE_SIZE,
            errors);
    keepAliveTime = ConfigurationServiceHelper.checkForLongKey(configurationService, CONFIG_KEY_KEEP_ALIVE_TIME,
            errors);

    ConfigurationServiceHelper.errorCheck(errors);

    tpe = new ThreadPoolExecutor(poolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(jobQueueSize));

    final boolean firstThreadStarted = tpe.prestartCoreThread();

    if (!firstThreadStarted) {
        tpe.shutdown();

        final String msg = "Failed to prestart initial thread";
        log.error(msg);
        throw new ComponentConfigurationException(msg);
    }
}

From source file:com.turn.griffin.control.GriffinControlManager.java

public GriffinControlManager(GriffinModule griffinModule) {

    Preconditions.checkNotNull(griffinModule);
    this.griffinModule = griffinModule;

    Preconditions.checkState(!StringUtils.isBlank(GriffinModule.ZOOKEEPER), "Zookeeper is not defined");
    Preconditions.checkState(!StringUtils.isBlank(GriffinModule.BROKERS), "Brokers are not defined");
    String zookeeper = GriffinModule.ZOOKEEPER;
    String brokers = GriffinModule.BROKERS;

    /* Start the consumer before the producer to trigger topic creation */
    /* Start control channel consumer */
    this.incomingCntrlMsgQueue = new ArrayBlockingQueue<>(CONTROL_TOPIC_CONSUMER_QUEUE_SIZE);

    /* The groupId should be unique to avoid conflict with other consumers running on this machine */
    String consumerGroupId = GriffinKafkaTopicNameUtil
            .getControlTopicConsumerGroupId(new String[] { getMyServerId(), this.getClass().getSimpleName() });
    this.controlConsumer = new GriffinConsumer(zookeeper, consumerGroupId,
            GriffinKafkaTopicNameUtil.getControlTopicNameForConsumer(), CONTROL_TOPIC_CONSUMER_THREADS,
            new Properties(), incomingCntrlMsgQueue);

    /* Start a producer for control messages */
    this.controlProducer = new GriffinProducer(brokers);

    /* Thread pool to process all control commands and messages */
    this.controlThreadPool = Executors.newScheduledThreadPool(CONTROL_THREAD_POOL_COUNT);

    /* Start resource discovery */
    scheduleControlJob(/*from  w w  w  .  j  a va2s  .co m*/
            new GriffinResourceDiscoveryTask(this, GriffinResourceDiscoveryTask.Action.SEND_GLOBAL_FILE_INFO),
            new Random().nextInt(GriffinModule.RESOURCE_DISCOVERY_INTERVAL_MS), TimeUnit.MILLISECONDS);

    /* A thread to create suitable runnable for incoming control messages */
    scheduleControlJob(this, 0, TimeUnit.SECONDS);
}

From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java

public AbstractTomcatTest(final Protocol protocol, final int maxThreads) {
    this(protocol);
    executor = new ThreadPoolExecutor(0, maxThreads, 10, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(maxThreads));
}

From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java

JournalNodeJournalSyncer(List<InetSocketAddress> journalNodes, InetSocketAddress journalNode,
        Configuration conf) {/*from  w w w  .  ja v a  2  s.  c o  m*/
    this.journalNodes = journalNodes;
    this.journalNode = journalNode;
    this.taskQueue = new ArrayBlockingQueue<SyncTask>(10);

    // timeout for getting manifest and reading log segments
    this.httpConnectReadTimeoutMs = conf.getInt(JournalConfigKeys.DFS_QJOURNAL_HTTP_TIMEOUT_KEY,
            JournalConfigKeys.DFS_QJOURNAL_HTTP_TIMEOUT_DEFAULT);
}

From source file:org.apache.hadoop.hive.ql.exec.tez.TezSessionPoolManager.java

public void setupPool(HiveConf conf) throws InterruptedException {

    String defaultQueues = HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_SERVER2_TEZ_DEFAULT_QUEUES);
    int numSessions = conf.getIntVar(HiveConf.ConfVars.HIVE_SERVER2_TEZ_SESSIONS_PER_DEFAULT_QUEUE);

    // the list of queues is a comma separated list.
    String defaultQueueList[] = defaultQueues.split(",");
    defaultQueuePool = new ArrayBlockingQueue<TezSessionState>(numSessions * defaultQueueList.length);
    this.initConf = conf;
    /*/*w  w  w  . j a  va  2 s .c o m*/
     *  with this the ordering of sessions in the queue will be (with 2 sessions 3 queues)
     *  s1q1, s1q2, s1q3, s2q1, s2q2, s2q3 there by ensuring uniform distribution of
     *  the sessions across queues at least to begin with. Then as sessions get freed up, the list
     *  may change this ordering.
     */
    blockingQueueLength = 0;
    for (int i = 0; i < numSessions; i++) {
        for (String queue : defaultQueueList) {
            if (queue.length() == 0) {
                continue;
            }
            TezSessionState sessionState = createSession(TezSessionState.makeSessionId());
            sessionState.setQueueName(queue);
            sessionState.setDefault();
            LOG.info("Created new tez session for queue: " + queue + " with session id: "
                    + sessionState.getSessionId());
            defaultQueuePool.put(sessionState);
            blockingQueueLength++;
        }
    }
}

From source file:org.apache.nifi.processors.standard.util.TestPutTCPCommon.java

@Before
public void setup() throws Exception {
    recvQueue = new ArrayBlockingQueue<List<Byte>>(BUFFER_SIZE);
    runner = TestRunners.newTestRunner(PutTCP.class);
    runner.setVariable(SERVER_VARIABLE, TCP_SERVER_ADDRESS);
}

From source file:edu.fullerton.framemonitor.FrameMonitor.java

public void startTasks() {
    PrintStream log = System.out;

    // Built in watchers are very efficient but only work for native file systems 
    // But they do not work on nfs volumes
    for (PlotQueDefn pqd : watchQueDefn) {
        File dir = new File(pqd.getDirName());
        if (!dir.exists()) {
            System.err.println("Directory: " + pqd.getDirName() + " does not exist.");
        } else {/*from   w  w  w  . j  a  v  a2  s.  c o  m*/
            // create a list of queues that will process the files found
            BlockingQueue<File> outQue = new ArrayBlockingQueue<>(128);
            List<BlockingQueue<File>> fileQueue = new ArrayList<>();
            fileQueue.add(outQue);

            // create the processes that will consume the queues
            QueueProcessor pq = new IgnoreQueue(outQue, log);
            Thread pqt = new Thread(pq);
            pqt.setName(pqd.getQueName() + " - consumer");
            pqt.start();
            processors.add(pqt);

            FrameWatcher w = new FrameWatcher(pqd.getDirName(), pqd.getFrameType(), log, fileQueue);
            Thread wt = new Thread(w);
            wt.setName(pqd.getQueName() + " - watcher");
            wt.start();
            watchers.add(wt);
        }
    }
    // The Apache commons listeners poll so they also work on nfs volumes
    for (PlotQueDefn pqd : listenQueDefn) {
        File dir = new File(pqd.getDirName());
        if (!dir.exists()) {
            System.err.println("Directory: " + pqd.getDirName() + " does not exist.");
        } else {
            // create a list of queues that will process the files found
            BlockingQueue<File> outQue = new ArrayBlockingQueue<>(128);
            List<BlockingQueue<File>> fileQueue = new ArrayList<>();
            fileQueue.add(outQue);

            // create the processes that will consume the queues
            QueueProcessor pq = new IgnoreQueue(outQue, log);
            Thread pqt = new Thread(pq);
            pqt.setName(pqd.getQueName() + " - consumer");
            pqt.start();
            processors.add(pqt);

            FileAlterationObserver observer = new FileAlterationObserver(pqd.getDirName());
            ChangeListener cl = new ChangeListener(log, outQue);
            observer.addListener(cl);
            monitor.addObserver(observer);
        }
    }
    try {
        monitor.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    System.out.println("Stopping monitor.");
                    monitor.stop();
                } catch (Exception ignored) {
                }
            }
        }));
    } catch (Exception ex) {
        Logger.getLogger(FrameMonitor.class.getName()).log(Level.SEVERE, null, ex);
    }
}