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.moilioncircle.redis.replicator.RedisSocketReplicator.java

public RedisSocketReplicator(String host, int port, Configuration configuration) {
    this.host = host;
    this.port = port;
    this.configuration = configuration;
    this.eventQueue = new ArrayBlockingQueue<>(configuration.getEventQueueSize());
    builtInCommandParserRegister();/*from  w  w w  . jav a  2s .  c o  m*/
    addExceptionListener(new DefaultExceptionListener());
}

From source file:com.taobao.tair.comm.TairClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TairClientException {
    if (isDebugEnabled) {
        LOGGER.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }//from ww w  .j a va 2 s  . co  m
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {
            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tair server error [" + packet.getChid() + "], tair server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed :"
                    + !session.isConnected();
            LOGGER.warn(error);
            TairResponse response = new TairResponse();
            response.setRequestId(packet.getChid());
            response.setResponse(new TairClientException(error));
            try {
                putResponse(packet.getChid(), response.getResponse());
            } catch (TairClientException e) {
                // IGNORE,should not happen
            }
            // close this session
            if (session.isConnected())
                session.close();
            else
                clientFactory.removeClient(key);
        }

    });
    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) {
            throw new TairClientException("tair client invoke timeout,timeout is: " + timeout
                    + ",requestId is: " + packet.getChid() + "request type:" + packet.getClass().getName());
        } else if (response instanceof TairClientException) {
            throw (TairClientException) response;
        }
    } catch (InterruptedException e) {
        throw new TairClientException("tair client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        LOGGER.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
        LOGGER.debug("current responses size: " + responses.size());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:org.apache.hadoop.hbase.ipc.FifoRpcScheduler.java

@Override
public void start() {
    this.executor = new ThreadPoolExecutor(handlerCount, handlerCount, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(maxQueueLength),
            new DaemonThreadFactory("FifoRpcScheduler.handler"), new ThreadPoolExecutor.CallerRunsPolicy());
}

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  w w .j  a v  a2 s.  co  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.jmangos.commons.threadpool.CommonThreadPoolManager.java

/**
 * @see org.jmangos.commons.service.Service#start()
 *///from  www .j av a2 s. c om
@PostConstruct
@Override
public void start() {

    final int scheduledPoolSize = ThreadPoolConfig.GENERAL_POOL;
    this.scheduledPool = new ScheduledThreadPoolExecutor(scheduledPoolSize);
    this.scheduledPool.prestartAllCoreThreads();

    final int instantPoolSize = ThreadPoolConfig.GENERAL_POOL;
    this.instantPool = new ThreadPoolExecutor(instantPoolSize, instantPoolSize, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(100000));
    this.instantPool.prestartAllCoreThreads();
}

From source file:org.jax.maanova.plot.RenderChartImageTask.java

/**
 * Constructor/*  w w w.  java2s.c  o  m*/
 * @param chartRenderingInfo
 *          the chart rendering info
 */
public RenderChartImageTask(ChartRenderingInfo chartRenderingInfo) {
    this.chartRenderingInfo = chartRenderingInfo;
    this.bufferedImageQueue = new ArrayBlockingQueue<BufferedImage>(1);
    this.renderRequestQueue = new ArrayBlockingQueue<Object>(1);
}

From source file:org.apache.reef.vortex.api.VortexAggregateFuture.java

@Private
public VortexAggregateFuture(final Executor executor, final Map<Integer, TInput> taskletIdInputMap,
        final FutureCallback<AggregateResult<TInput, TOutput>> callbackHandler) {
    this.executor = executor;
    this.taskletIdInputMap = new ConcurrentHashMap<>(taskletIdInputMap);
    this.resultQueue = new ArrayBlockingQueue<>(taskletIdInputMap.size());
    this.callbackHandler = callbackHandler;
}

From source file:com.esri.geoevent.clusterSimulator.ui.CertificateCheckerDialog.java

@Override
public boolean allowConnection(final X509Certificate[] chain) {
    if (trustedCerts.contains(chain[0])) {
        return true;
    }/*from www.  j  a v  a  2 s . c o m*/
    final ArrayBlockingQueue<Boolean> responseQueue = new ArrayBlockingQueue<Boolean>(1);
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                final Stage dialog = new Stage();
                dialog.initModality(Modality.APPLICATION_MODAL);
                dialog.initOwner(MainApplication.primaryStage);
                dialog.setTitle("Certificate Check");
                FXMLLoader loader = new FXMLLoader(getClass().getResource("CertificateCheckerDialog.fxml"));
                Parent parent = (Parent) loader.load();
                CertCheckController controller = (CertCheckController) loader.getController();
                controller.certText.setText(chain[0].toString());
                Scene scene = new Scene(parent);
                dialog.setScene(scene);
                dialog.showAndWait();
                responseQueue.put(Boolean.valueOf(controller.allowConnection));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    if (Platform.isFxApplicationThread()) {
        runnable.run();
    } else {
        Platform.runLater(runnable);
    }

    try {
        boolean retVal = responseQueue.take();
        if (retVal) {
            trustedCerts.add(chain[0]);
        }
        return retVal;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.loklak.tools.storage.JsonRandomAccessFile.java

/**
 * if a JsonRandomAccessFile object in initiated, it must be wrapped with a Thread object and started.
 * @param dumpFile//ww w.ja  va2  s  .co  m
 * @param concurrency
 * @throws IOException
 */
public JsonRandomAccessFile(final File dumpFile, final int concurrency) throws IOException {
    super(dumpFile, "rw");
    this.file = dumpFile;
    this.concurrency = concurrency;
    this.jsonline = new ArrayBlockingQueue<>(1000);
}

From source file:ubic.gemma.core.apps.ExpressionExperimentDataFileGeneratorCli.java

@Override
protected Exception doWork(String[] args) {

    Exception exp = this.processCommandLine(args);
    if (exp != null) {
        return exp;
    }//  w w w. jav a2 s  .  co m

    BlockingQueue<BioAssaySet> queue = new ArrayBlockingQueue<>(expressionExperiments.size());

    // Add the Experiments to the queue for processing
    for (BioAssaySet ee : expressionExperiments) {
        if (ee instanceof ExpressionExperiment) {
            try {
                queue.put(ee);
            } catch (InterruptedException ie) {
                AbstractCLI.log.info(ie);
            }
        } else {
            throw new UnsupportedOperationException("Can't handle non-EE BioAssaySets yet");
        }

    }

    // Inner class for processing the experiments
    class Worker extends Thread {
        private SecurityContext context;
        private BlockingQueue<BioAssaySet> q;

        private Worker(BlockingQueue<BioAssaySet> q, SecurityContext context) {
            this.context = context;
            this.q = q;
        }

        @Override
        public void run() {

            SecurityContextHolder.setContext(this.context);

            while (true) {
                BioAssaySet ee = q.poll();
                if (ee == null) {
                    break;
                }
                AbstractCLI.log.info("Processing Experiment: " + ee.getName());
                ExpressionExperimentDataFileGeneratorCli.this.processExperiment((ExpressionExperiment) ee);

            }

        }
    }

    final SecurityContext context = SecurityContextHolder.getContext();

    Collection<Thread> threads = new ArrayList<>();

    for (int i = 1; i <= this.numThreads; i++) {
        Worker worker = new Worker(queue, context);
        threads.add(worker);
        AbstractCLI.log.info("Starting thread " + i);
        worker.start();
    }

    this.waitForThreadPoolCompletion(threads);

    this.summarizeProcessing();

    return null;

}