Example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

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

Introduction

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

Prototype

public LinkedBlockingQueue() 

Source Link

Document

Creates a LinkedBlockingQueue with a capacity of Integer#MAX_VALUE .

Usage

From source file:se.vgregion.pubsub.push.impl.DefaultPushSubscriberVerifyTest.java

@Test
@Transactional/*from  w  w  w.  j a v  a 2  s.co m*/
@Rollback
public void verify() throws Exception {
    final LinkedBlockingQueue<HttpRequest> requests = new LinkedBlockingQueue<HttpRequest>();

    server.register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            requests.add(request);

            response.setEntity(
                    new StringEntity(getQueryParamValue(request.getRequestLine().getUri(), "hub.challenge")));
        }
    });

    subscriber.verify(SubscriptionMode.SUBSCRIBE);

    Assert.assertEquals(1, requests.size());

    HttpRequest actualRequest = requests.poll();
    String requestUri = actualRequest.getRequestLine().getUri();
    Assert.assertEquals("subscribe", getQueryParamValue(requestUri, "hub.mode"));
    Assert.assertEquals(subscriber.getTopic().toString(),
            URLDecoder.decode(getQueryParamValue(requestUri, "hub.topic"), "UTF-8"));
    Assert.assertNotNull(getQueryParamValue(requestUri, "hub.challenge"));
    Assert.assertEquals("123", getQueryParamValue(requestUri, "hub.lease_seconds"));
    Assert.assertEquals(subscriber.getVerifyToken(), getQueryParamValue(requestUri, "hub.verify_token"));
}

From source file:org.alfresco.extension.bulkimport.impl.BulkImportThreadPoolExecutor.java

public BulkImportThreadPoolExecutor(final ThreadPauser pauser, final int threadPoolSize,
        final int queueCapacity, final long keepAliveTime, final TimeUnit keepAliveTimeUnit) {
    super(threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize, // Core pool size
            threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize, // Max pool size (same as core pool size)
            keepAliveTime <= 0 ? DEFAULT_KEEP_ALIVE_TIME : keepAliveTime, // Keep alive
            keepAliveTimeUnit == null ? DEFAULT_KEEP_ALIVE_TIME_UNIT : keepAliveTimeUnit, // Keep alive units
            new LinkedBlockingQueue<Runnable>(), // Queue of maximum size
            new BulkImportThreadFactory(), // Thread factory
            new ThreadPoolExecutor.AbortPolicy()); // Rejection handler (shouldn't ever be called, due to the use of a semaphone before task submission)

    this.queueCapacity = queueCapacity;
    this.pauser = pauser;

    final int queuePlusPoolSize = (queueCapacity <= 0 ? DEFAULT_QUEUE_CAPACITY : queueCapacity)
            + (threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize);
    this.queueSemaphore = new Semaphore(queuePlusPoolSize);

    if (debug(log))
        debug(log, "Created new bulk import thread pool." + " Thread Pool Size="
                + (threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize) + ", Queue Capacity="
                + ((queueCapacity <= 0 ? DEFAULT_QUEUE_CAPACITY : queueCapacity) + 2) + ", Keep Alive Time="
                + (keepAliveTime <= 0 ? DEFAULT_KEEP_ALIVE_TIME : keepAliveTime) + " "
                + String.valueOf(keepAliveTimeUnit == null ? DEFAULT_KEEP_ALIVE_TIME_UNIT : keepAliveTimeUnit));
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);/* ww  w.ja va  2s  .  c  o  m*/
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}

From source file:com.dsclab.loader.app.Loader.java

public static void load(Configs prop)
        throws SQLException, ClassNotFoundException, InterruptedException, ExecutionException {
    int readThread = prop.getReadThread();
    int writeThread = prop.getWriteThread();
    ExecutorService readExecutor = Executors.newFixedThreadPool(readThread);
    ExecutorService writeExecutor = Executors.newFixedThreadPool(writeThread);
    LOG.info("Start load: writeThread:" + writeThread + ", readThread:" + readThread);
    BlockingQueue<List<String>> contentQueue = new LinkedBlockingQueue<>();

    int tableCount = tableTask.size();
    int sum = 0;//from  w w w.  ja v  a  2 s . c o  m
    for (int i = 0; i < tableCount; i++) {
        sum = sum + tableTask.get(i).getTaskSqlList().size();
    }
    for (int i = 0; i < sum; i++) {
        readExecutor.submit(new ProducerThread(prop.getInputURL(), contentQueue));
        writeExecutor.submit(new ConsumerThread(prop.getOutputURL(), contentQueue));
    }

    readExecutor.shutdown();
    readExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    System.out.println("[CHIA7712] read threads end");
    writeExecutor.shutdown();
    writeExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    System.out.println("[CHIA7712] write threads end");
}

From source file:com.nextgis.maplib.display.SimpleFeatureRenderer.java

@Override
public void runDraw(final GISDisplay display) {
    GeoEnvelope env = display.getBounds();
    final VectorLayer vectorLayer = (VectorLayer) mLayer;
    GeoEnvelope layerEnv = vectorLayer.getExtents();

    if (!env.intersects(layerEnv)) {
        vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
        return;//from ww  w  .  j  a  v  a 2  s . c o  m
    }

    //add drawing routine
    final List<VectorCacheItem> cache = vectorLayer.getVectorCache();

    //TODO: more than one thread for drawing (divide the geometry cache array on several parts)
    //TODO: think about display syncronization in drawing points/lines/polygons

    mDrawThreadPool = new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
            new LinkedBlockingQueue<Runnable>(), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    try {
                        executor.getQueue().put(r);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        //throw new RuntimeException("Interrupted while submitting task", e);
                    }
                }
            });

    if (cache.size() == 0) {
        vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
        return;
    }

    mDrawThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

            for (int i = 0; i < cache.size(); i++) {
                VectorCacheItem item = cache.get(i);

                GeoGeometry geometry = item.getGeoGeometry();
                mStyle.onDraw(geometry, display);

                synchronized (mLayer) {
                    float percent = (float) i / cache.size();
                    vectorLayer.onDrawFinished(vectorLayer.getId(), percent);
                }

                vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
                //Log.d(TAG, "percent: " + percent + " complete: " + mDrawThreadPool.getCompletedTaskCount() + " task count: " + mDrawThreadPool.getTaskCount());
            }
        }
    });
}

From source file:com.linuxbox.enkive.message.search.TaskPoolAsyncMessageSearchService.java

public TaskPoolAsyncMessageSearchService(int corePoolSize, int maxPoolSize, int keepAliveTime) {
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    searchExecutor = new CancellableProcessExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
            queue);/*from   w  w w.  j av a  2 s . co  m*/
}

From source file:org.geoserver.wps.executor.DefaultProcessManager.java

public void setMaxAsynchronousProcesses(int maxAsynchronousProcesses) {
    if (asynchService == null) {
        // create a fixed size pool. If we allow a delta between core and max 
        // the pool will create new threads only if the queue is full, but the linked queue never is
        asynchService = new ThreadPoolExecutor(maxAsynchronousProcesses, maxAsynchronousProcesses, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    } else {//from  w  w w .  j  av  a 2  s  .c  om
        asynchService.setCorePoolSize(maxAsynchronousProcesses);
        asynchService.setMaximumPoolSize(maxAsynchronousProcesses);
    }
}

From source file:se.vgregion.pubsub.push.impl.DefaultPushSubscriberPublishTest.java

@Test
public void publish() throws Exception {

    subscriber = new DefaultPushSubscriber(UnitTestConstants.TOPIC, buildTestUrl("/"), UnitTestConstants.FUTURE,
            UnitTestConstants.UPDATED1, 100, "verify", UnitTestConstants.SECRET, true);

    final LinkedBlockingQueue<HttpRequest> issuedRequests = new LinkedBlockingQueue<HttpRequest>();
    final LinkedBlockingQueue<byte[]> issuedRequestBodies = new LinkedBlockingQueue<byte[]>();
    server.register("/*", new HttpRequestHandler() {
        @Override/*from  w  w w . j av a  2  s .c  o m*/
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            issuedRequests.add(request);

            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            entity.writeTo(buffer);
            issuedRequestBodies.add(buffer.toByteArray());
        }
    });

    Feed feed = new FeedBuilder(ContentType.ATOM).id("e1")
            .entry(new EntryBuilder().id("f1").updated(new DateTime()).build())
            .entry(new EntryBuilder().id("f2").updated(UnitTestConstants.UPDATED1.minusHours(1)).build())
            .build();

    subscriber.publish(feed, null);

    // subscriber should be updated
    Assert.assertEquals(new DateTime(), subscriber.getLastUpdated());

    HttpRequest request = issuedRequests.poll(10000, TimeUnit.MILLISECONDS);
    Assert.assertNotNull(request);
    Assert.assertEquals(ContentType.ATOM.toString(), request.getFirstHeader("Content-Type").getValue());

    // verify HMAC header
    Assert.assertEquals("sha1=1356b52665408a17af46803a7988e48d40d1fb75",
            request.getFirstHeader("X-Hub-Signature").getValue());

    // verify content
    Assert.assertTrue(request instanceof HttpEntityEnclosingRequest);

    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

    Assert.assertNotNull(entity);

    Document actualAtom = new Builder().build(new ByteArrayInputStream(issuedRequestBodies.poll()));

    Assert.assertEquals(1, actualAtom.getRootElement().getChildElements("entry", Namespaces.ATOM).size());

}

From source file:rk.java.compute.cep.ComputeService.java

public ComputeService(final int numberOfTickSources, final int threadPoolSize, IPriceEventSink eventBus) {
    this(new LinkedBlockingQueue<IPriceTick>(), numberOfTickSources, eventBus);
    executorService = Executors.newFixedThreadPool(threadPoolSize);
    ecs = new ExecutorCompletionService<StopWatch>(executorService);
}

From source file:ninja.eivind.hotsreplayuploader.services.UploaderService.java

public UploaderService() throws IOException {
    logger.info("Instantiating " + getClass().getSimpleName());
    uploadQueue = new LinkedBlockingQueue<>();
    files = FXCollections.observableArrayList();
    setExecutor(Executors.newCachedThreadPool());
    logger.info("Instantiated " + getClass().getSimpleName());
}