Search in sources :

Example 66 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project hbase by apache.

the class TestMobCompactor method createThreadPool.

private static ExecutorService createThreadPool(Configuration conf) {
    int maxThreads = 10;
    long keepAliveTime = 60;
    final SynchronousQueue<Runnable> queue = new SynchronousQueue<>();
    ThreadPoolExecutor pool = new ThreadPoolExecutor(1, maxThreads, keepAliveTime, TimeUnit.SECONDS, queue, Threads.newDaemonThreadFactory("MobFileCompactionChore"), new RejectedExecutionHandler() {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                // waiting for a thread to pick up instead of throwing exceptions.
                queue.put(r);
            } catch (InterruptedException e) {
                throw new RejectedExecutionException(e);
            }
        }
    });
    ((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
    return pool;
}
Also used : RejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler) SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 67 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project k-9 by k9mail.

the class K9 method registerReceivers.

/**
     * Register BroadcastReceivers programmatically because doing it from manifest
     * would make K-9 auto-start. We don't want auto-start because the initialization
     * sequence isn't safe while some events occur (SD card unmount).
     */
protected void registerReceivers() {
    final StorageGoneReceiver receiver = new StorageGoneReceiver();
    final IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_EJECT);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    filter.addDataScheme("file");
    final BlockingQueue<Handler> queue = new SynchronousQueue<Handler>();
    // starting a new thread to handle unmount events
    new Thread(new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            try {
                queue.put(new Handler());
            } catch (InterruptedException e) {
                Timber.e(e);
            }
            Looper.loop();
        }
    }, "Unmount-thread").start();
    try {
        final Handler storageGoneHandler = queue.take();
        registerReceiver(receiver, filter, null, storageGoneHandler);
        Timber.i("Registered: unmount receiver");
    } catch (InterruptedException e) {
        Timber.e(e, "Unable to register unmount receiver");
    }
    registerReceiver(new ShutdownReceiver(), new IntentFilter(Intent.ACTION_SHUTDOWN));
    Timber.i("Registered: shutdown receiver");
}
Also used : StorageGoneReceiver(com.fsck.k9.service.StorageGoneReceiver) IntentFilter(android.content.IntentFilter) SynchronousQueue(java.util.concurrent.SynchronousQueue) Handler(android.os.Handler) ShutdownReceiver(com.fsck.k9.service.ShutdownReceiver)

Example 68 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project okhttp by square.

the class CallTest method asyncResponseCanBeConsumedLater.

@Test
public void asyncResponseCanBeConsumedLater() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));
    Request request = new Request.Builder().url(server.url("/")).header("User-Agent", "SyncApiTest").build();
    final BlockingQueue<Response> responseRef = new SynchronousQueue<>();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            throw new AssertionError();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                responseRef.put(response);
            } catch (InterruptedException e) {
                throw new AssertionError();
            }
        }
    });
    Response response = responseRef.take();
    assertEquals(200, response.code());
    assertEquals("abc", response.body().string());
    // Make another request just to confirm that that connection can be reused...
    executeSynchronously("/").assertBody("def");
    // New connection.
    assertEquals(0, server.takeRequest().getSequenceNumber());
    // Connection reused.
    assertEquals(1, server.takeRequest().getSequenceNumber());
    // ... even before we close the response body!
    response.body().close();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) SynchronousQueue(java.util.concurrent.SynchronousQueue) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) Test(org.junit.Test)

Example 69 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project nhin-d by DirectProject.

the class DNSSocketServer method start.

/**
	 * Starts the socket server and initializes the dispatch threads.  After this method has been called, the server will start accepting
	 * DNS requests.
	 * @throws DNSException
	 */
public void start() throws DNSException {
    if (running.get() != true) {
        // create the accept thread
        running.set(true);
        dnsRequestService = new ThreadPoolExecutor(0, settings.getMaxActiveRequests(), 120L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        socketAcceptService = Executors.newSingleThreadExecutor();
        socketAcceptService.execute(getSocketAcceptTask());
        serverStartTime = System.currentTimeMillis();
    } else
        LOGGER.info("Start requested, but socket server is already running.");
}
Also used : SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 70 with SynchronousQueue

use of java.util.concurrent.SynchronousQueue in project camel by apache.

the class DefaultThreadPoolFactory method newThreadPool.

public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize, boolean allowCoreThreadTimeOut, RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException {
    // the core pool size must be 0 or higher
    if (corePoolSize < 0) {
        throw new IllegalArgumentException("CorePoolSize must be >= 0, was " + corePoolSize);
    }
    // validate max >= core
    if (maxPoolSize < corePoolSize) {
        throw new IllegalArgumentException("MaxPoolSize must be >= corePoolSize, was " + maxPoolSize + " >= " + corePoolSize);
    }
    BlockingQueue<Runnable> workQueue;
    if (corePoolSize == 0 && maxQueueSize <= 0) {
        // use a synchronous queue for direct-handover (no tasks stored on the queue)
        workQueue = new SynchronousQueue<Runnable>();
        // and force 1 as pool size to be able to create the thread pool by the JDK
        corePoolSize = 1;
        maxPoolSize = 1;
    } else if (maxQueueSize <= 0) {
        // use a synchronous queue for direct-handover (no tasks stored on the queue)
        workQueue = new SynchronousQueue<Runnable>();
    } else {
        // bounded task queue to store tasks on the queue
        workQueue = new LinkedBlockingQueue<Runnable>(maxQueueSize);
    }
    ThreadPoolExecutor answer = new RejectableThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
    answer.setThreadFactory(threadFactory);
    answer.allowCoreThreadTimeOut(allowCoreThreadTimeOut);
    if (rejectedExecutionHandler == null) {
        rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    }
    answer.setRejectedExecutionHandler(rejectedExecutionHandler);
    return answer;
}
Also used : SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) RejectableThreadPoolExecutor(org.apache.camel.util.concurrent.RejectableThreadPoolExecutor) RejectableScheduledThreadPoolExecutor(org.apache.camel.util.concurrent.RejectableScheduledThreadPoolExecutor) RejectableThreadPoolExecutor(org.apache.camel.util.concurrent.RejectableThreadPoolExecutor) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue)

Aggregations

SynchronousQueue (java.util.concurrent.SynchronousQueue)120 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)64 ExecutorService (java.util.concurrent.ExecutorService)21 ThreadFactory (java.util.concurrent.ThreadFactory)15 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)13 ArrayList (java.util.ArrayList)12 RejectedExecutionHandler (java.util.concurrent.RejectedExecutionHandler)10 IOException (java.io.IOException)9 Test (org.junit.Test)9 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 InputStream (java.io.InputStream)7 OutputStream (java.io.OutputStream)7 BlockingQueue (java.util.concurrent.BlockingQueue)7 XMPPException (org.jivesoftware.smack.XMPPException)7 Future (java.util.concurrent.Future)6 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 XMPPConnection (org.jivesoftware.smack.XMPPConnection)5 List (java.util.List)4