Example usage for java.util.concurrent SynchronousQueue SynchronousQueue

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

Introduction

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

Prototype

public SynchronousQueue() 

Source Link

Document

Creates a SynchronousQueue with nonfair access policy.

Usage

From source file:natalia.dymnikova.util.ThreadPoolBeans.java

public ExecutorService firstPriorityTasksExecutor0() {
    final ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("first-priority-%03d")
            .setDaemon(true).build();// w ww .j a v a  2 s .c  o m

    final ExecutorService executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<>(), factory);

    log.debug("Constructed first priority tasks executor {}", executor);
    return executor;
}

From source file:gridool.deployment.PeerClassLoader.java

@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
    BlockingQueue<GridTaskResult> resultQueue = new SynchronousQueue<GridTaskResult>();
    String jobId = "p2p-classloading_" + resultQueue.hashCode();
    responseQueue.addResponseQueue(jobId, resultQueue);

    if (LOG.isInfoEnabled()) {
        LOG.info("Loading a class '" + name + "' from " + remoteNode);
    }//  w w  w .j  av  a 2s  . c  o  m

    GridNode localNode = communicator.getLocalNode();
    final GridGetClassTask task = new GridGetClassTask(jobId, localNode, name);
    try {// send a class-loading request
        communicator.sendTaskRequest(task, remoteNode);
    } catch (GridException e) {
        throw new ClassNotFoundException("Failed sending a GridGetClassTask of the class: " + name, e);
    }

    // Receive a requested class
    final GridTaskResult result;
    try {
        result = resultQueue.take(); // TODO timeout
    } catch (InterruptedException e) {
        throw new ClassNotFoundException("An error caused while receiving a class: " + name, e);
    }
    final ClassData clazz = result.getResult();
    assert (clazz != null);
    byte[] clazzData = clazz.getClassData();
    long ts = clazz.getTimestamp();
    final Class<?> definedClazz = parentLdr.defineClassIfNeeded(name, clazzData, ts);

    // define enclosing classes
    ClassData enclosingClass = clazz.getEnclosingClass();
    while (enclosingClass != null) {
        defineClass(enclosingClass, parentLdr);
        enclosingClass = enclosingClass.getEnclosingClass();
    }

    return definedClazz;
}

From source file:org.jitsi.sphinx4http.server.Session.java

/**
 * transcribe the given audio file and send each retrieved word back
 * immediately. The word will be a JSON object with values, word, start,
 * end, filler'./*w w  w. j a v a2 s.  c o  m*/
 * @param audioFile the audio file to transcribe
 * @param out the outputstream to write each word results to immediately
 * @return JSON array with every uttered word in the audio file
 */
public JSONArray chunkedTranscribe(File audioFile, PrintWriter out) throws IOException {
    logger.trace("started chunked transcribing of " + "audio file with id : {}", id);

    try (InputStream in = new FileInputStream(audioFile)) {
        // create a thread to immediately get the word result out
        // of the synchronousQueue
        final SynchronousQueue<WordResult> results = new SynchronousQueue<>();
        final ArrayList<WordResult> storedResults = new ArrayList<>();
        //make sure the printwriter does not close because it's needed
        //else where to finish the object
        final PrintWriter printWriter = new PrintWriter(out);
        Thread queueManager = new Thread(new Runnable() {
            @Override
            public void run() {
                //listen for the first word outside of the loop
                //to prevent a trailing "," at the end of the transcription
                //json array
                try {
                    WordResult word = results.take();
                    logger.trace("retrieved word outside loop\"{}\"", word.toString());
                    storedResults.add(word);
                    JSONObject toSend = builder.buildWordObject(word);
                    printWriter.write("," + toSend.toJSONString());
                    printWriter.flush();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        //blocks until result is retrieved
                        WordResult word = results.take();
                        logger.trace("retrieved word \"{}\"", word.toString());
                        storedResults.add(word);
                        JSONObject toSend = builder.buildWordObject(word);
                        printWriter.write("," + toSend.toJSONString());
                        printWriter.flush();
                    } catch (InterruptedException e) {
                        //make sure the thread ends
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        queueManager.start();
        transcriber.transcribeSynchronous(in, results);
        //stop the thread as the transcribing is done
        queueManager.interrupt();

        return builder.buildSpeechToTextResult(storedResults);
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedPriorityQueue.java

@Test
public void testSortingWhileTaking() throws Exception {
    Timing timing = new Timing();
    DistributedPriorityQueue<Integer> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();//from  w  w w.j a v  a2 s .c o  m
    try {
        final BlockingQueue<Integer> blockingQueue = new SynchronousQueue<Integer>();
        QueueConsumer<Integer> consumer = new QueueConsumer<Integer>() {
            @Override
            public void consumeMessage(Integer message) throws Exception {
                blockingQueue.put(message);
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0);
        queue.start();

        for (int i = 0; i < 10; ++i) {
            queue.put(i, 10);
        }

        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(0));
        timing.sleepABit();
        queue.put(1000, 1); // lower priority
        timing.sleepABit();
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1)); // is in consumer already
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1000));
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:org.apache.hadoop.hbase.procedure.ProcedureCoordinator.java

/**
 * Default thread pool for the procedure
 *
 * @param coordName//from w  w  w  .j  a v  a2s . c o  m
 * @param opThreads the maximum number of threads to allow in the pool
 * @param keepAliveMillis the maximum time (ms) that excess idle threads will wait for new tasks
 */
public static ThreadPoolExecutor defaultPool(String coordName, int opThreads, long keepAliveMillis) {
    return new ThreadPoolExecutor(1, opThreads, keepAliveMillis, TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>(),
            new DaemonThreadFactory("(" + coordName + ")-proc-coordinator-pool"));
}

From source file:org.nuxeo.ecm.core.event.impl.PostCommitEventExecutor.java

public PostCommitEventExecutor() {
    // use as much thread as needed up to MAX_POOL_SIZE
    // keep them alive a moment for reuse
    // have all threads torn down when there is no work to do
    ThreadFactory threadFactory = new NamedThreadFactory("Nuxeo-Event-PostCommit-");
    executor = new ThreadPoolExecutor(0, MAX_POOL_SIZE, KEEP_ALIVE_TIME_SECOND, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), threadFactory);
    ((ThreadPoolExecutor) executor).allowCoreThreadTimeOut(true);
}

From source file:org.helios.netty.jmx.ThreadPoolFactory.java

/**
 * Creates a new ThreadPool//from w  w w . j  a  va  2 s . c  om
 * @param domain The JMX domain where the MBean will be published 
 * @param name The name property for the MBean ObjectName
 */
private ThreadPoolFactory(String domain, String name) {
    super(0, Integer.MAX_VALUE, 50L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
    setThreadFactory(this);
    this.name = name;
    try {
        objectName = new ObjectName(domain + ":service=ThreadPool,name=" + name);
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, objectName);
        threadingMetrics.put(name, poolMetrics);
        ManagementFactory.getPlatformMBeanServer().addNotificationListener(MetricCollector.OBJECT_NAME, this,
                this, null);
        String prefix = "threadPools.[" + name + "].";
        for (String s : points) {
            metricNames.add(prefix + s);
        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to register management interface for pool [" + domain + "/" + name + "]", e);
    }

}

From source file:com.amazonaws.services.simpleworkflow.flow.worker.GenericActivityWorker.java

@Override
protected TaskPoller createPoller() {
    ThreadPoolExecutor tasksExecutor = new ThreadPoolExecutor(1, taskExecutorThreadPoolSize, 1,
            TimeUnit.MINUTES, new SynchronousQueue<Runnable>());
    tasksExecutor.setThreadFactory(//www  .jav  a 2  s.c  o m
            new ExecutorThreadFactory(ACTIVITY_THREAD_NAME_PREFIX + " " + getTaskListToPoll() + " "));
    tasksExecutor.setRejectedExecutionHandler(new BlockCallerPolicy());
    return new ActivityTaskPoller(service, domain, getTaskListToPoll(), activityImplementationFactory,
            tasksExecutor);
}

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  va2s.  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:oculus.aperture.capture.phantom.impl.PhantomRenderer.java

/**
 * Constructs a new renderer instance.//from   ww  w.ja va  2s .  c  o  m
 * @param contentService
 *       The CMS
 * @param cmsStore
 *       The store id
 * @param exePath
 *       The path to phantom
 * @param rootRef
 *       The root reference of the incoming url
 * @param workerId
 *       A unique worker id.
 */
public PhantomRenderer(ContentService contentService, String exePath, String taskPageUrl, String workerId,
        String sslCertificatePath, String sslIgnoreErrors) {
    this.contentService = contentService;
    taskQueue = new SynchronousQueue<Map<String, Object>>();

    try {
        this.worker = new PhantomCommandLineCapture(exePath, this, taskPageUrl, sslCertificatePath,
                sslIgnoreErrors);

    } catch (IOException e) {
        throw new RuntimeException("Failed to start phantom JS process: " + exePath, e);
    }

    cmsResult = new SynchronousQueue<DocumentDescriptor>();
    imageResult = new SynchronousQueue<ImageData>();
}