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:com.nextgis.mobile.map.MapBase.java

/**
 * The base map class// w  ww  .  ja  v a  2  s.c  om
 */

public MapBase(Context context) {
    super(context);

    mName = context.getString(R.string.default_map_name);
    mNewId = 0;
    mListeners = new ArrayList<MapEventListener>();
    mLayers = new ArrayList<Layer>();

    mCPUTotalCount = Runtime.getRuntime().availableProcessors() - 1;
    if (mCPUTotalCount < 1)
        mCPUTotalCount = 1;
    mContinueDrawing = false;

    newtworkUtil = new NetworkUtil(context);

    createHandler();

    //initialise display
    mDisplay = new GISDisplay(context);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    File defaultPath = context.getExternalFilesDir(PREFS_MAP);
    mMapPath = new File(sharedPreferences.getString(KEY_PREF_MAP_PATH, defaultPath.getPath()));

    mDrawWorkQueue = new LinkedBlockingQueue<Runnable>();
    mDrawThreadPool = new ThreadPoolExecutor(1, mCPUTotalCount, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
            mDrawWorkQueue);

    setKeepScreenOn(true);
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testAsyncInitialPopulation() throws Exception {
    PathChildrenCache cache = null;//from w w  w  .j av  a2  s. c  o  m
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {
        client.start();

        client.create().forPath("/test");
        client.create().forPath("/test/one", "hey there".getBytes());

        final BlockingQueue<PathChildrenCacheEvent> events = new LinkedBlockingQueue<PathChildrenCacheEvent>();
        cache = new PathChildrenCache(client, "/test", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                events.offer(event);
            }
        });
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        PathChildrenCacheEvent event = events.poll(10, TimeUnit.SECONDS);
        Assert.assertEquals(event.getType(), PathChildrenCacheEvent.Type.CHILD_ADDED);

        event = events.poll(10, TimeUnit.SECONDS);
        Assert.assertEquals(event.getType(), PathChildrenCacheEvent.Type.INITIALIZED);
        Assert.assertEquals(event.getInitialData().size(), 1);
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:ch.ethz.dcg.jukefox.manager.libraryimport.AbstractAlbumCoverFetcherThread.java

public AbstractAlbumCoverFetcherThread(AbstractCollectionModelManager collectionModelManager,
        List<AlbumCoverFetcherListener> listeners, ImportState importState) {
    this.albumProvider = collectionModelManager.getAlbumProvider();
    this.otherDataProvider = collectionModelManager.getOtherDataProvider();
    this.modifyProvider = collectionModelManager.getModifyProvider();
    this.inQueue = new LinkedBlockingQueue<Integer>();
    this.importState = importState;
    createFileNameFilter();/*from   ww w  . java 2 s  .com*/
    initializeHttpClient();
}

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

@Test
public void maxUsage_MultiThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(10, 10, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);// w w w .ja  v  a2 s  .co  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 Multithreaded 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 Multithreaded overall usage: " + actualUsage);
}

From source file:org.esigate.test.cases.PerformanceTestCase.java

/**
 * Execute la tache avec plusieurs Threads
 * /*from w  w w .j  ava  2  s.com*/
 * @param request
 * @return
 * @throws Exception
 */
private long execute(HttpGetRequestRunnable request, int numberOfRequests, int threads) throws Exception {
    connectionManager = new PoolingHttpClientConnectionManager();
    httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setMaxConnTotal(threads)
            .setMaxConnPerRoute(threads).setDefaultRequestConfig(
                    RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build())
            .build();
    // Warm up
    request.run();

    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS, queue);

    long start = System.currentTimeMillis();
    threadPool.prestartAllCoreThreads();
    for (int i = 0; i < numberOfRequests; i++) {
        threadPool.submit(request);
    }
    threadPool.shutdown();

    // wait maximum 20 s
    threadPool.awaitTermination(200, TimeUnit.SECONDS);
    connectionManager.shutdown();

    if (request.exception != null) {
        throw new AssertionFailedError(
                "Exception for request " + request.url + " after " + request.count + " requests",
                request.exception);
    }
    if (threadPool.getCompletedTaskCount() < threadPool.getTaskCount()) {
        // All task were not executed
        String msg = request.url + " : Only " + threadPool.getCompletedTaskCount() + "/"
                + threadPool.getTaskCount() + " have been renderered " + " => Maybe a performance issue";
        threadPool.shutdownNow();
        fail(msg);
    }

    long end = System.currentTimeMillis();
    long execTime = end - start;
    LOG.debug("Executed request " + request.url + " " + numberOfRequests + " times with " + threads
            + " threads in " + execTime + "ms");
    return execTime;

}

From source file:org.apache.axis2.util.threadpool.ThreadPool.java

protected ThreadPoolExecutor createDefaultExecutor(final String name, final int priority,
        final boolean daemon) {
    ThreadPoolExecutor rc;//ww w . j a v  a  2s.  c o m
    if (maxPoolSize == Integer.MAX_VALUE) {
        rc = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 10, TimeUnit.SECONDS, new SynchronousQueue(),
                new DefaultThreadFactory(name, daemon, priority));
    } else {
        rc = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 10, TimeUnit.SECONDS, new LinkedBlockingQueue(),
                new DefaultThreadFactory(name, daemon, priority));
    }
    // FIXME: This API is only in JDK 1.6 - Use reflection?        
    //        rc.allowCoreThreadTimeOut(true);
    return rc;
}

From source file:com.netflix.dyno.queues.redis.RedisDynoQueue.java

public RedisDynoQueue(String redisKeyPrefix, String queueName, Set<String> allShards, String shardName,
        ExecutorService dynoCallExecutor) {
    this.redisKeyPrefix = redisKeyPrefix;
    this.queueName = queueName;
    this.allShards = allShards.stream().collect(Collectors.toList());
    this.shardName = shardName;
    this.messageStoreKey = redisKeyPrefix + ".MESSAGE." + queueName;
    this.myQueueShard = getQueueShardKey(queueName, shardName);

    ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    om.setSerializationInclusion(Include.NON_NULL);
    om.setSerializationInclusion(Include.NON_EMPTY);
    om.disable(SerializationFeature.INDENT_OUTPUT);

    this.om = om;
    this.monitor = new QueueMonitor(queueName, shardName);
    this.prefetchedIds = new LinkedBlockingQueue<>();
    this.executorService = dynoCallExecutor;

    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> processUnacks(), unackScheduleInMS,
            unackScheduleInMS, TimeUnit.MILLISECONDS);
    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> prefetchIds(), 0, 10, TimeUnit.MILLISECONDS);

    logger.info(RedisDynoQueue.class.getName() + " is ready to serve " + queueName);

}

From source file:com.netflix.curator.framework.imps.TestFramework.java

@Test
public void testNamespaceWithWatcher() throws Exception {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa")
            .retryPolicy(new RetryOneTime(1)).build();
    client.start();/*from  ww  w.  j a v a2  s .c o m*/
    try {
        final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    queue.put(event.getPath());
                } catch (InterruptedException e) {
                    throw new Error(e);
                }
            }
        };
        client.create().forPath("/base");
        client.getChildren().usingWatcher(watcher).forPath("/base");
        client.create().forPath("/base/child");

        String path = queue.take();
        Assert.assertEquals(path, "/base");
    } finally {
        client.close();
    }
}

From source file:com.fusesource.forge.jmstest.benchmark.command.BenchmarkCoordinator.java

public void start() {
    synchronized (started) {
        if (!started) {
            log().debug("Starting Benchmark Coordinator.");
            ReleaseManager.getInstance().register(this);
            benchmarks = new HashMap<String, BenchmarkRunner>();
            executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
            started = true;//ww  w .  ja  v a  2 s .  co  m
        }
    }
}

From source file:com.test.HibernateDerbyLockingTest.java

public void testJDBC() throws Exception {
    final DerbyTemplate template = new DerbyTemplate();
    try {//from   w  w w  .j  a v  a2s  .c  o  m
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute(
                        "CREATE TABLE TEST(\n" + "ID CHAR(36) NOT NULL,\n" + "NAME VARCHAR(255)\n" + ")");
            }
        });
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("INSERT INTO TEST(ID, NAME) VALUES('12345', 'Bob')");
            }
        });

        final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> submit = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rs");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        try {
                            Thread.sleep(2000);
                        } catch (Throwable t) {
                        }
                        System.out.println("one");
                        queue.add("one");
                        try {
                            Thread.sleep(500);
                        } catch (Throwable t) {
                        }
                    }
                });
                return null;
            }
        });
        Thread.sleep(500);
        Future<?> submit2 = executorService.submit(new Callable<Object>() {
            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rr");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        queue.add("two");
                        System.out.println("two");
                    }
                });
                return null;
            }
        });
        submit.get();
        submit2.get();
        assertEquals("one", queue.poll(3, TimeUnit.SECONDS));
        assertEquals("two", queue.poll(3, TimeUnit.SECONDS));
    } finally {
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("DROP TABLE TEST");
            }
        });
    }
}