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:cc.solr.lucene.store.BufferStore.java

private static BlockingQueue<byte[]> setupBuffers(int bufferSize, int count) {
    BlockingQueue<byte[]> queue = new ArrayBlockingQueue<byte[]>(count);
    for (int i = 0; i < count; i++) {
        queue.add(new byte[bufferSize]);
    }//w  ww .  j a  va2  s . co m
    return queue;
}

From source file:ar.com.zauber.commons.message.impl.mail.BufferedServiceEmailNotificationStrategy.java

/**
 * Creates the BufferedServiceEmailNotificationStrategy.
 *//* www. ja  v a2s. c o m*/
public BufferedServiceEmailNotificationStrategy(final EmailService emailService, final int qtyFlush,
        final String senderDomain, final String senderAccount) {
    Validate.notNull(emailService);
    Validate.isTrue(qtyFlush > 0);
    Validate.notEmpty(senderDomain);
    Validate.notEmpty(senderAccount);

    this.queue = new ArrayBlockingQueue<SendEmailDTO>(qtyFlush);
    this.emailService = emailService;
    this.senderDomain = senderDomain;
    this.senderAccount = senderAccount;
}

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

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

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

From source file:org.lilyproject.repository.bulk.serial.ThreadedRecordWriter.java

public ThreadedRecordWriter(String lilyZk, int numThreads, String repositoryName, String tableName,
        boolean bulkMode) {
    this.lilyZk = lilyZk;
    this.repositoryName = repositoryName;
    this.tableName = tableName;
    this.bulkMode = bulkMode;
    executor = new ThreadPoolExecutor(numThreads, numThreads, 10, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(5));
    executor.setRejectedExecutionHandler(new WaitPolicy());
    threadLocalBulkIngesters = new ThreadLocal<BulkIngester>();
    bulkIngesters = Collections.synchronizedList(Lists.<BulkIngester>newArrayList());
}

From source file:com.scoreflex.ScoreflexJobQueue.java

/**
 * Creates a queue with the specified name
 * @param queueName The name of the queue, which determines the queue's storage location
 * @param capacity The maximum number of jobs the queue can hold
 *///from w w w .j a  v a2  s.co m
public ScoreflexJobQueue(String queueName, int capacity) {
    mQueueName = queueName;
    mQueue = new ArrayBlockingQueue<ScoreflexJobQueue.InternalJob>(capacity);
    restore();
}

From source file:io.bitsquare.common.util.Utilities.java

public static ThreadPoolExecutor getThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize,
        long keepAliveTimeInSec) {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(name).setDaemon(true).build();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeInSec,
            TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize), threadFactory);
    executor.allowCoreThreadTimeOut(true);
    executor.setRejectedExecutionHandler((r, e) -> {
        log.debug("RejectedExecutionHandler called");
    });//  w w w . jav  a2  s  . c  o  m
    return executor;
}

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

@Test
public void testInstantiation() throws InterruptedException {
    filter = pipeline.newGStreamerFilter("videoflip method=horizontal-flip").build();

    Assert.assertNotNull(filter);/*from  w w w  .  j ava2  s  .  c  o  m*/

    player.connect(filter);

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

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

    player.play();
    Assert.assertNotNull(eosEvents.poll(7, SECONDS));
    filter.release();
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSCxfContinuationsTest.java

private void doTestContinuation(String pathSegment) throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);

    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/1", "1",
            "CXF in Action1", startSignal, doneSignal));
    startSignal.countDown();//from www.j a v a2  s.co m
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
}

From source file:com.twofortyfouram.locale.sdk.host.test.Junit4SupportLoaderTestCase.java

/**
 * Runs a Loader synchronously and returns the result of the load. The loader will
 * be started, stopped, and destroyed by this method so it cannot be reused.
 *
 * @param loader The loader to run synchronously
 * @return The result from the loader/*from   w  w w .j  a v  a 2  s.com*/
 */
public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
    // The test thread blocks on this queue until the loader puts it's result in
    final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);

    // This callback runs on the "main" thread and unblocks the test thread
    // when it puts the result into the blocking queue
    final Loader.OnLoadCompleteListener<T> listener = new Loader.OnLoadCompleteListener<T>() {
        @Override
        public void onLoadComplete(Loader<T> completedLoader, T data) {
            // Shut the loader down
            completedLoader.unregisterListener(this);
            completedLoader.stopLoading();
            completedLoader.reset();

            // Store the result, unblocking the test thread
            queue.add(data);
        }
    };

    // This handler runs on the "main" thread of the process since AsyncTask
    // is documented as needing to run on the main thread and many Loaders use
    // AsyncTask
    final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            loader.registerListener(0, listener);
            loader.startLoading();
        }
    };

    // Ask the main thread to start the loading process
    mainThreadHandler.sendEmptyMessage(0);

    // Block on the queue waiting for the result of the load to be inserted
    T result;
    while (true) {
        try {
            result = queue.take();
            break;
        } catch (InterruptedException e) {
            throw new RuntimeException("waiting thread interrupted", e);
        }
    }

    return result;
}

From source file:code.google.nfs.rpc.client.AbstractClient.java

private Object invokeSyncIntern(RequestWrapper wrapper) throws Exception {
    long beginTime = System.currentTimeMillis();
    ArrayBlockingQueue<Object> responseQueue = new ArrayBlockingQueue<Object>(1);
    responses.put(wrapper.getId(), responseQueue);
    ResponseWrapper responseWrapper = null;
    try {// w w w.j  a v a 2  s . c om
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug("client ready to send message,request id: " + wrapper.getId());
        }
        getClientFactory().checkSendLimit();
        sendRequest(wrapper, wrapper.getTimeout());
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug(
                    "client write message to send buffer,wait for response,request id: " + wrapper.getId());
        }
    } catch (Exception e) {
        responses.remove(wrapper.getId());
        responseQueue = null;
        LOGGER.error("send request to os sendbuffer error", e);
        throw e;
    }
    Object result = null;
    try {
        result = responseQueue.poll(wrapper.getTimeout() - (System.currentTimeMillis() - beginTime),
                TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        responses.remove(wrapper.getId());
        LOGGER.error("Get response error", e);
        throw new Exception("Get response error", e);
    }
    responses.remove(wrapper.getId());

    if (PRINT_CONSUME_MINTIME > 0 && isWarnEnabled) {
        long consumeTime = System.currentTimeMillis() - beginTime;
        if (consumeTime > PRINT_CONSUME_MINTIME) {
            LOGGER.warn("client.invokeSync consume time: " + consumeTime + " ms, server is: " + getServerIP()
                    + ":" + getServerPort() + " request id is:" + wrapper.getId());
        }
    }
    if (result == null) {
        String errorMsg = "receive response timeout(" + wrapper.getTimeout() + " ms),server is: "
                + getServerIP() + ":" + getServerPort() + " request id is:" + wrapper.getId();
        throw new Exception(errorMsg);
    }

    if (result instanceof ResponseWrapper) {
        responseWrapper = (ResponseWrapper) result;
    } else if (result instanceof List) {
        @SuppressWarnings("unchecked")
        List<ResponseWrapper> responseWrappers = (List<ResponseWrapper>) result;
        for (ResponseWrapper response : responseWrappers) {
            if (response.getRequestId() == wrapper.getId()) {
                responseWrapper = response;
            } else {
                putResponse(response);
            }
        }
    } else {
        throw new Exception("only receive ResponseWrapper or List as response");
    }
    try {
        // do deserialize in business threadpool
        if (responseWrapper.getResponse() instanceof byte[]) {
            String responseClassName = null;
            if (responseWrapper.getResponseClassName() != null) {
                responseClassName = new String(responseWrapper.getResponseClassName());
            }
            // avoid server no return object
            if (((byte[]) responseWrapper.getResponse()).length == 0) {
                responseWrapper.setResponse(null);
            } else {
                Object responseObject = Codecs.getDecoder(responseWrapper.getCodecType())
                        .decode(responseClassName, (byte[]) responseWrapper.getResponse());
                if (responseObject instanceof Throwable) {
                    responseWrapper.setException((Throwable) responseObject);
                } else {
                    responseWrapper.setResponse(responseObject);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Deserialize response object error", e);
        throw new Exception("Deserialize response object error", e);
    }
    if (responseWrapper.isError()) {
        Throwable t = responseWrapper.getException();
        t.fillInStackTrace();
        String errorMsg = "server error,server is: " + getServerIP() + ":" + getServerPort() + " request id is:"
                + wrapper.getId();
        LOGGER.error(errorMsg, t);
        throw new Exception(errorMsg, t);
    }
    return responseWrapper.getResponse();
}