Example usage for java.util.concurrent BlockingQueue take

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

Introduction

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

Prototype

E take() throws InterruptedException;

Source Link

Document

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Usage

From source file:DelayedJob.java

public static void main(String[] args) throws InterruptedException {
    BlockingQueue<DelayedJob> queue = new DelayQueue<>();
    Instant now = Instant.now();

    queue.put(new DelayedJob("A", now.plusSeconds(9)));
    queue.put(new DelayedJob("B", now.plusSeconds(3)));
    queue.put(new DelayedJob("C", now.plusSeconds(6)));
    queue.put(new DelayedJob("D", now.plusSeconds(1)));

    while (queue.size() > 0) {
        System.out.println("started...");
        DelayedJob job = queue.take();
        System.out.println("Job: " + job);
    }/*from ww w  .jav a  2 s .  co  m*/
    System.out.println("Finished.");
}

From source file:org.sourcepit.docker.watcher.Main.java

public static void main(String[] args) throws IOException {

    final HttpClientFactory clientFactory = new HttpClientFactory() {
        @Override/*from  www. j  av  a  2 s  .  c o m*/
        public CloseableHttpClient createHttpClient() {
            return HttpClients.createDefault();
        }
    };

    final String dockerDaemonUri = "http://192.168.56.101:2375";
    final String consulAgentUri = "http://192.168.56.101:8500";

    final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>();

    final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(),
            consulAgentUri);

    final Thread containerStateDispatcher = new Thread("Consul Forwarder") {
        @Override
        public void run() {
            while (true) {
                try {
                    consulForwarder.forward(queue.take());
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    LOG.error("Error while forwarding Docker container state to Consul.", e);
                }
            }
        }
    };
    containerStateDispatcher.start();

    final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) {
        @Override
        protected void handle(List<JsonObject> containerState) {
            queue.add(containerState);
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            watcher.stop();
            while (containerStateDispatcher.isAlive()) {
                containerStateDispatcher.interrupt();
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    watcher.start();
}

From source file:ca.ualberta.exemplar.core.Exemplar.java

public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser cli = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "shows this message");
    options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)");
    options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)");

    CommandLine line = null;/*from w  w w . j  a v a  2s.  c o  m*/

    try {
        line = cli.parse(options, rawArgs);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "malt");

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar", options);
        System.exit(0);
    }

    if (args.length != 2) {
        System.out.println("error: exemplar requires an input file and output file.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar <input> <output>", options);
        System.exit(0);
    }

    File input = new File(args[0]);
    File output = new File(args[1]);

    String benchmarkType = line.getOptionValue("benchmark", "");
    if (!benchmarkType.isEmpty()) {
        if (benchmarkType.equals("binary")) {
            BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName);
            evaluation.runAndTime();
            System.exit(0);
        } else {
            if (benchmarkType.equals("nary")) {
                BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName);
                evaluation.runAndTime();
                System.exit(0);
            } else {
                System.out.println("error: benchmark option has to be either 'binary' or 'nary'.");
                System.exit(0);
            }
        }
    }

    Parser parser = null;
    if (parserName.equals("stanford")) {
        parser = new ParserStanford();
    } else {
        if (parserName.equals("malt")) {
            parser = new ParserMalt();
        } else {
            System.out.println(parserName + " is not a valid parser.");
            System.exit(0);
        }
    }

    System.out.println("Starting EXEMPLAR...");

    RelationExtraction exemplar = null;
    try {
        exemplar = new RelationExtraction(parser);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
    PlainTextReader reader = null;
    reader = new PlainTextReader(inputQueue, input);

    Thread readerThread = new Thread(reader);
    readerThread.start();

    PrintStream statementsOut = null;

    try {
        statementsOut = new PrintStream(output, "UTF-8");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.exit(0);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        System.exit(0);
    }

    statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence");

    while (true) {
        String doc = null;
        try {
            doc = inputQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (doc.isEmpty()) {
            break;
        }

        List<RelationInstance> instances = exemplar.extractRelations(doc);

        for (RelationInstance instance : instances) {

            // Output SUBJ arguments in a separate field, for clarity
            boolean first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("SUBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }

            // Output the original relation
            statementsOut.print("\t" + instance.getOriginalRelation() + "\t");

            // Output the DOBJ arguments, followed by POBJ
            first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("DOBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.startsWith("POBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            statementsOut.print("\t" + instance.getNormalizedRelation());
            statementsOut.print("\t" + instance.getSentence());
            statementsOut.println();
        }
    }

    System.out.println("Done!");
    statementsOut.close();

}

From source file:Main.java

public static <T> T take(BlockingQueue<T> queue) {
    try {/*w  w  w . j  a  v a 2s  . com*/
        return queue.take();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:Main.java

public static <T> T sureTake(BlockingQueue<T> audio) {
    while (true) {
        try {/*from www .  ja va 2s . c om*/
            return audio.take();
        } catch (InterruptedException e) {
        }
    }
}

From source file:org.diorite.impl.log.QueueLogAppender.java

public static String getNextLogEvent(final String queueName) {
    QUEUE_LOCK.readLock().lock();//from  ww w .  ja  v a2  s  .co m
    final BlockingQueue<String> queue = QUEUES.get(queueName);
    QUEUE_LOCK.readLock().unlock();
    if (queue != null) {
        try {
            return queue.take();
        } catch (final InterruptedException ignored) {
        }
    }
    return null;
}

From source file:fi.jumi.core.ipc.dirs.DirectoryObserverTest.java

private static List<Path> takeAtLeast(int count, BlockingQueue<Path> src) throws InterruptedException {
    List<Path> taken = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        taken.add(src.take());
    }/*from   w  w  w .j a  v a2s  .c o m*/
    Path p;
    while ((p = src.poll()) != null) {
        taken.add(p);
    }
    return taken;
}

From source file:com.yahoo.storm.yarn.MasterServer.java

private static void initAndStartLauncher(final StormAMRMClient client,
        final BlockingQueue<Container> launcherQueue) {
    Thread thread = new Thread() {
        Container container;/*from w w  w .  j  a v a  2  s  .  co  m*/

        @Override
        public void run() {
            while (client.getServiceState() == Service.STATE.STARTED
                    && !Thread.currentThread().isInterrupted()) {
                try {
                    container = launcherQueue.take();
                    LOG.info("LAUNCHER: Taking container with id (" + container.getId() + ") from the queue.");
                    if (client.supervisorsAreToRun()) {
                        LOG.info("LAUNCHER: Supervisors are to run, so launching container id ("
                                + container.getId() + ")");
                        client.launchSupervisorOnContainer(container);
                    } else {
                        // Do nothing
                        LOG.info("LAUNCHER: Supervisors are not to run, so not launching container id ("
                                + container.getId() + ")");
                    }
                } catch (InterruptedException e) {
                    if (client.getServiceState() == Service.STATE.STARTED) {
                        LOG.error("Launcher thread interrupted : ", e);
                        System.exit(1);
                    }
                    return;
                } catch (IOException e) {
                    LOG.error("Launcher thread I/O exception : ", e);
                    System.exit(1);
                }
            }
        }
    };
    thread.start();
}

From source file:org.loklak.android.wok.Harvester.java

/**
 * if the given list of timelines contain at least the wanted minimum size of
 * messages, they are flushed from the queue and combined into a new timeline
 * // www.ja  va2  s .  c  om
 * @param dumptl
 * @param order
 * @param minsize
 * @return
 */
public static Timeline takeTimelineMin(final BlockingQueue<Timeline> dumptl, final Timeline.Order order,
        final int minsize) {
    int c = 0;
    for (Timeline tl : dumptl)
        c += tl.size();
    if (c < minsize)
        return new Timeline(order);

    // now flush the timeline queue completely
    Timeline tl = new Timeline(order);
    try {
        while (dumptl.size() > 0) {
            Timeline tl0 = dumptl.take();
            if (tl0 == null)
                return tl;
            tl.putAll(tl0);
        }
        return tl;
    } catch (InterruptedException e) {
        return tl;
    }
}

From source file:com.twitter.hbc.example.FilterStreamExample.java

public static void run(String consumerKey, String consumerSecret, String token, String secret)
        throws Exception {
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
    StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
    // add some track terms
    endpoint.trackTerms(Lists.newArrayList("#AAPBreakUp"));

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    // Authentication auth = new BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    Client client = new ClientBuilder().hosts(Constants.STREAM_HOST).endpoint(endpoint).authentication(auth)
            .processor(new StringDelimitedProcessor(queue)).build();

    // Establish a connection
    client.connect();// www  . ja  v  a 2 s.  c  om

    buildDS();
    // Do whatever needs to be done with messages
    int Limit = 20;
    for (int msgRead = 0; msgRead < Limit; msgRead++) {
        String msg = queue.take();
        JSONObject json = new JSONObject(msg);
        String tweet = (String) json.get("text");
        System.out.println(tweet + "Sentiment =" + classifyText(tweet));
    }

    client.stop();

}