Example usage for java.util.concurrent SynchronousQueue take

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

Introduction

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

Prototype

public E take() throws InterruptedException 

Source Link

Document

Retrieves and removes the head of this queue, waiting if necessary for another thread to insert it.

Usage

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'./*from  w  ww  .  j  a va2s  .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:org.apache.hedwig.server.netty.TestPubSubServer.java

@Test(timeout = 60000)
public void testUncaughtExceptionInNettyThread() throws Exception {

    SynchronousQueue<Throwable> queue = new SynchronousQueue<Throwable>();
    RecordingUncaughtExceptionHandler uncaughtExceptionHandler = new RecordingUncaughtExceptionHandler(queue);
    final int port = PortManager.nextFreePort();

    PubSubServer server = startServer(uncaughtExceptionHandler, port, new TopicManagerInstantiator() {

        @Override// w w w. j a v  a2 s.c  om
        public TopicManager instantiateTopicManager() throws IOException {
            return new AbstractTopicManager(new ServerConfiguration(),
                    Executors.newSingleThreadScheduledExecutor()) {
                @Override
                protected void realGetOwner(ByteString topic, boolean shouldClaim,
                        Callback<HedwigSocketAddress> cb, Object ctx) {
                    throw new RuntimeException("this exception should be uncaught");
                }

                @Override
                protected void postReleaseCleanup(ByteString topic, Callback<Void> cb, Object ctx) {
                }
            };
        }
    });

    runPublishRequest(port);
    assertEquals(RuntimeException.class, queue.take().getClass());
    server.shutdown();
}

From source file:org.apache.hedwig.server.netty.TestPubSubServer.java

@Test(timeout = 60000)
public void testUncaughtExceptionInZKThread() throws Exception {

    SynchronousQueue<Throwable> queue = new SynchronousQueue<Throwable>();
    RecordingUncaughtExceptionHandler uncaughtExceptionHandler = new RecordingUncaughtExceptionHandler(queue);
    final int port = PortManager.nextFreePort();
    final String hostPort = "127.0.0.1:" + PortManager.nextFreePort();

    PubSubServer server = startServer(uncaughtExceptionHandler, port, new TopicManagerInstantiator() {

        @Override/*from   w  w  w  .  jav a  2  s .c  o m*/
        public TopicManager instantiateTopicManager() throws IOException {
            return new AbstractTopicManager(new ServerConfiguration(),
                    Executors.newSingleThreadScheduledExecutor()) {

                @Override
                protected void realGetOwner(ByteString topic, boolean shouldClaim,
                        Callback<HedwigSocketAddress> cb, Object ctx) {
                    ZooKeeper zookeeper;
                    try {
                        zookeeper = new ZooKeeper(hostPort, 60000, new Watcher() {
                            @Override
                            public void process(WatchedEvent event) {
                                // TODO Auto-generated method stub

                            }
                        });
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    zookeeper.getData("/fake", false, new SafeAsyncZKCallback.DataCallback() {
                        @Override
                        public void safeProcessResult(int rc, String path, Object ctx, byte[] data,
                                org.apache.zookeeper.data.Stat stat) {
                            throw new RuntimeException("This should go to the uncaught exception handler");
                        }

                    }, null);
                }

                @Override
                protected void postReleaseCleanup(ByteString topic, Callback<Void> cb, Object ctx) {
                }
            };
        }
    });

    runPublishRequest(port);
    assertEquals(RuntimeException.class, queue.take().getClass());
    server.shutdown();
}