Example usage for java.util Queue poll

List of usage examples for java.util Queue poll

Introduction

In this page you can find the example usage for java.util Queue poll.

Prototype

E poll();

Source Link

Document

Retrieves and removes the head of this queue, or returns null if this queue is empty.

Usage

From source file:org.eclipse.scada.da.utils.daemon.DaemonStarter.java

public static void main(final String[] args) throws Exception {
    if (args.length == 0) {
        throw new RuntimeException("syntax: DaemonStarter <daemon class name>");
    }//from   www  .j  av  a  2s . c om

    final Queue<String> argList = new LinkedList<String>();
    argList.addAll(Arrays.asList(args));

    new DaemonStarter(Class.forName(argList.poll()), argList.toArray(new String[0]));

    while (true) {
        Thread.sleep(1000);
    }
}

From source file:Main.java

public static void main(String[] args) {
    Queue<String> queue = new LinkedList<String>();

    queue.add("A");
    queue.add("B");

    queue.offer("C");
    queue.offer("D");

    System.out.println("remove: " + queue.remove());

    System.out.println("element: " + queue.element());

    System.out.println("poll: " + queue.poll());

    System.out.println("peek: " + queue.peek());
}

From source file:Main.java

public static void main(String[] args) {
    Queue<String> queue = new LinkedList<String>();
    queue.offer("First");
    queue.offer("Second");
    queue.offer("Third");
    queue.offer("Fourth");

    System.out.println("Size: " + queue.size());

    System.out.println("Queue head using peek   : " + queue.peek());
    System.out.println("Queue head using element: " + queue.element());

    Object data;/* w ww.j  av  a2s  . com*/
    while ((data = queue.poll()) != null) {
        System.out.println(data);
    }
}

From source file:org.deeplearning4j.examples.unsupervised.sequenceanomalydetection.SequenceAnomalyDetection.java

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

    String dataPath = new ClassPathResource("/anomalysequencedata").getFile().getPath();
    File modelFile = new File(dataPath + File.separatorChar + "anomalyDetectionModel.gz");
    DataSetIterator trainIterator = new AnomalyDataSetIterator(dataPath + File.separatorChar + "ads.csv",
            trainBatchSize);//  w  w  w.  j  a  va 2 s. c om
    DataSetIterator testIterator = new AnomalyDataSetIterator(dataPath + File.separatorChar + "test.csv",
            testBatchSize);

    MultiLayerNetwork net = true ? createModel(trainIterator.inputColumns(), trainIterator.totalOutcomes())
            : MultiLayerNetwork.load(modelFile, true);
    UIServer uiServer = UIServer.getInstance();
    StatsStorage statsStorage = new FileStatsStorage(
            new File(System.getProperty("java.io.tmpdir"), "ui-stats.dl4j"));
    uiServer.attach(statsStorage);

    DataNormalization normalizer = new NormalizerStandardize();
    normalizer.fit(trainIterator); //Collect training data statistics
    trainIterator.reset();
    trainIterator.setPreProcessor(normalizer);
    testIterator.setPreProcessor(normalizer); //Note: using training normalization statistics
    NormalizerSerializer.getDefault().write(normalizer,
            dataPath + File.separatorChar + "anomalyDetectionNormlizer.ty");

    // training
    net.setListeners(new StatsListener(statsStorage), new ScoreIterationListener(10));
    net.fit(trainIterator, numEpochs);

    // save model to disk
    ModelSerializer.writeModel(net, modelFile, true);

    List<Pair<Double, String>> evalList = new ArrayList<>();
    Queue<String> queue = ((AnomalyDataSetIterator) testIterator).getCurrentLines();
    double totalScore = 0;
    while (testIterator.hasNext()) {
        DataSet ds = testIterator.next();
        double score = net.score(ds);
        String currentLine = queue.poll();
        totalScore += score;
        evalList.add(new ImmutablePair<>(score, currentLine));
    }

    Collections.sort(evalList, Comparator.comparing(Pair::getLeft));
    Stack<String> anomalyData = new Stack<>();
    double threshold = totalScore / evalList.size();
    for (Pair<Double, String> pair : evalList) {
        double s = pair.getLeft();
        if (s > threshold) {
            anomalyData.push(pair.getRight());
        }
    }

    //output anomaly data
    System.out.println("based on the score, all anomaly data is following with descending order:\n");
    for (int i = anomalyData.size(); i > 0; i--) {
        System.out.println(anomalyData.pop());
    }

}

From source file:reactor.logback.DurableLogUtility.java

@SuppressWarnings("unchecked")
public static void main(String... args) throws ParseException, JoranException, IOException {
    Parser parser = new BasicParser();
    CommandLine cl = null;/*from w w w  .j a  v a 2  s .  c  om*/
    try {
        cl = parser.parse(OPTS, args);
    } catch (ParseException e) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("dlog", OPTS, true);
        System.exit(-1);
    }

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.reset();

    if (cl.hasOption("config")) {
        // Read Logback configuration
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);

        configurator.doConfigure(cl.getOptionValue("file", "logback.xml"));

        StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    } else {
        BasicConfigurator.configure(loggerContext);
    }

    Appender appender = null;
    if (cl.hasOption("output")) {
        String outputAppender = cl.getOptionValue("output", "console");
        appender = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).getAppender(outputAppender);
    }

    ChronicleTools.warmup();
    Chronicle chronicle = ChronicleQueueBuilder.indexed(cl.getOptionValue("path")).build();
    ExcerptTailer ex = chronicle.createTailer();

    Level level = Level.valueOf(cl.getOptionValue("level", "TRACE"));

    if (cl.hasOption("head")) {
        int lines = Integer.parseInt(cl.getOptionValue("head", "10"));
        for (int i = 0; i < lines; i++) {
            LoggingEvent evt = readLoggingEvent(ex, loggerContext);
            if (evt.getLevel().isGreaterOrEqual(level)) {
                writeEvent(evt, appender);
            }
        }
    } else if (cl.hasOption("tail")) {
        int lines = Integer.parseInt(cl.getOptionValue("tail", "10"));
        Queue<LoggingEvent> tail = new LinkedBlockingQueue<LoggingEvent>(lines);
        while (ex.nextIndex()) {
            LoggingEvent evt = readLoggingEvent(ex, loggerContext);
            if (!tail.offer(evt)) {
                tail.poll();
                tail.add(evt);
            }
        }
        LoggingEvent evt;
        while (null != (evt = tail.poll())) {
            if (evt.getLevel().isGreaterOrEqual(level)) {
                writeEvent(evt, appender);
            }
        }
    } else if (cl.hasOption("search")) {
        String regex = cl.getOptionValue("search");
        Pattern regexPatt = Pattern.compile(regex);
        while (ex.nextIndex()) {
            LoggingEvent evt = readLoggingEvent(ex, loggerContext);
            if (null != evt && evt.getLevel().isGreaterOrEqual(level)) {
                if (regexPatt.matcher(evt.getFormattedMessage()).matches()) {
                    writeEvent(evt, appender);
                }
            }
        }
    }

    loggerContext.stop();
    chronicle.close();
}

From source file:Main.java

public static void main(String[] args) {
    Queue<String> queue = new LinkedList<>();
    queue.add("Java");
    // offer() will work the same as add()
    queue.offer("SQL");
    queue.offer("CSS");
    queue.offer("XML");

    System.out.println("Queue: " + queue);

    // Let's remove elements until the queue is empty
    while (queue.peek() != null) {
        System.out.println("Head  Element: " + queue.peek());
        queue.remove();//from ww  w.  j  a  va 2  s. c o m
        System.out.println("Removed one  element from  Queue");
        System.out.println("Queue: " + queue);
    }
    System.out.println("queue.isEmpty(): " + queue.isEmpty());
    System.out.println("queue.peek(): " + queue.peek());
    System.out.println("queue.poll(): " + queue.poll());
    try {
        String str = queue.element();
        System.out.println("queue.element(): " + str);
        str = queue.remove();
        System.out.println("queue.remove(): " + str);
    } catch (NoSuchElementException e) {
        System.out.println("queue.remove(): Queue is  empty.");
    }
}

From source file:org.apache.flink.benchmark.Runner.java

public static void main(String[] args) throws Exception {
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().enableObjectReuse();
    env.getConfig().disableSysoutLogging();

    ParameterTool parameters = ParameterTool.fromArgs(args);

    if (!(parameters.has("p") && parameters.has("types") && parameters.has("algorithms"))) {
        printUsage();//from w ww.  j a v a 2  s.c om
        System.exit(-1);
    }

    int parallelism = parameters.getInt("p");
    env.setParallelism(parallelism);

    Set<IdType> types = new HashSet<>();

    if (parameters.get("types").equals("all")) {
        types.add(IdType.INT);
        types.add(IdType.LONG);
        types.add(IdType.STRING);
    } else {
        for (String type : parameters.get("types").split(",")) {
            if (type.toLowerCase().equals("int")) {
                types.add(IdType.INT);
            } else if (type.toLowerCase().equals("long")) {
                types.add(IdType.LONG);
            } else if (type.toLowerCase().equals("string")) {
                types.add(IdType.STRING);
            } else {
                printUsage();
                throw new RuntimeException("Unknown type: " + type);
            }
        }
    }

    Queue<RunnerWithScore> queue = new PriorityQueue<>();

    if (parameters.get("algorithms").equals("all")) {
        for (Map.Entry<String, Class> entry : AVAILABLE_ALGORITHMS.entrySet()) {
            for (IdType type : types) {
                AlgorithmRunner runner = (AlgorithmRunner) entry.getValue().newInstance();
                runner.initialize(type, SAMPLES, parallelism);
                runner.warmup(env);
                queue.add(new RunnerWithScore(runner, 1.0));
            }
        }
    } else {
        for (String algorithm : parameters.get("algorithms").split(",")) {
            double ratio = 1.0;
            if (algorithm.contains("=")) {
                String[] split = algorithm.split("=");
                algorithm = split[0];
                ratio = Double.parseDouble(split[1]);
            }

            if (AVAILABLE_ALGORITHMS.containsKey(algorithm.toLowerCase())) {
                Class clazz = AVAILABLE_ALGORITHMS.get(algorithm.toLowerCase());

                for (IdType type : types) {
                    AlgorithmRunner runner = (AlgorithmRunner) clazz.newInstance();
                    runner.initialize(type, SAMPLES, parallelism);
                    runner.warmup(env);
                    queue.add(new RunnerWithScore(runner, ratio));
                }
            } else {
                printUsage();
                throw new RuntimeException("Unknown algorithm: " + algorithm);
            }
        }
    }

    JsonFactory factory = new JsonFactory();

    while (queue.size() > 0) {
        RunnerWithScore current = queue.poll();
        AlgorithmRunner runner = current.getRunner();

        StringWriter writer = new StringWriter();
        JsonGenerator gen = factory.createGenerator(writer);
        gen.writeStartObject();
        gen.writeStringField("algorithm", runner.getClass().getSimpleName());

        boolean running = true;

        while (running) {
            try {
                runner.run(env, gen);
                running = false;
            } catch (ProgramInvocationException e) {
                // only suppress job cancellations
                if (!(e.getCause() instanceof JobCancellationException)) {
                    throw e;
                }
            }
        }

        JobExecutionResult result = env.getLastJobExecutionResult();

        long runtime_ms = result.getNetRuntime();
        gen.writeNumberField("runtime_ms", runtime_ms);
        current.credit(runtime_ms);

        if (!runner.finished()) {
            queue.add(current);
        }

        gen.writeObjectFieldStart("accumulators");
        for (Map.Entry<String, Object> accumulatorResult : result.getAllAccumulatorResults().entrySet()) {
            gen.writeStringField(accumulatorResult.getKey(), accumulatorResult.getValue().toString());
        }
        gen.writeEndObject();

        gen.writeEndObject();
        gen.close();
        System.out.println(writer.toString());
    }
}

From source file:amie.keys.CSAKey.java

public static void main(String[] args) throws IOException, InterruptedException {
    final Triple<MiningAssistant, Float, String> parsedArgs = parseArguments(args);
    final Set<Rule> output = new LinkedHashSet<>();

    // Helper object that contains the implementation for the calculation
    // of confidence and support
    // The file with the non-keys, one per line
    long timea = System.currentTimeMillis();
    List<List<String>> inputNonKeys = Utilities.parseNonKeysFile(parsedArgs.third);
    System.out.println(inputNonKeys.size() + " input non-keys");
    final List<List<String>> nonKeys = pruneBySupport(inputNonKeys, parsedArgs.second,
            parsedArgs.first.getKb());/*from  w  w  w . j a va 2 s.  c o m*/
    Collections.sort(nonKeys, new Comparator<List<String>>() {

        @Override
        public int compare(List<String> o1, List<String> o2) {
            int r = Integer.compare(o2.size(), o1.size());
            if (r == 0) {
                return Integer.compare(o2.hashCode(), o1.hashCode());
            }

            return r;
        }

    });
    System.out.println(nonKeys.size() + " non-keys after pruning");
    int totalLoad = computeLoad(nonKeys);
    System.out.println(totalLoad + " is the total load");
    int nThreads = Runtime.getRuntime().availableProcessors();
    //int batchSize = Math.max(Math.min(maxBatchSize, totalLoad / nThreads), minBatchSize);
    int batchSize = Math.max(Math.min(maxLoad, totalLoad / nThreads), minLoad);

    final Queue<int[]> chunks = new PriorityQueue(50, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return Integer.compare(o2[2], o1[2]);
        }

    });

    final HashSet<HashSet<Integer>> nonKeysInt = new HashSet<>();
    final HashMap<String, Integer> property2Id = new HashMap<>();
    final HashMap<Integer, String> id2Property = new HashMap<>();
    final List<Integer> propertiesList = new ArrayList<>();
    int support = (int) parsedArgs.second.floatValue();
    KB kb = parsedArgs.first.getKb();
    buildDictionaries(nonKeys, nonKeysInt, property2Id, id2Property, propertiesList, support, kb);
    final List<HashSet<Integer>> nonKeysIntList = new ArrayList<>(nonKeysInt);
    int start = 0;
    int[] nextIdx = nextIndex(nonKeysIntList, 0, batchSize);
    int end = nextIdx[0];
    int load = nextIdx[1];
    while (start < nonKeysIntList.size()) {
        int[] chunk = new int[] { start, end, load };
        chunks.add(chunk);
        start = end;
        nextIdx = nextIndex(nonKeysIntList, end, batchSize);
        end = nextIdx[0];
        load = nextIdx[1];
    }

    Thread[] threads = new Thread[Math.min(Runtime.getRuntime().availableProcessors(), chunks.size())];
    for (int i = 0; i < threads.length; ++i) {
        threads[i] = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    int[] chunk = null;
                    synchronized (chunks) {
                        if (!chunks.isEmpty()) {
                            chunk = chunks.poll();
                        } else {
                            break;
                        }
                    }
                    System.out.println("Processing chunk " + Arrays.toString(chunk));
                    mine(parsedArgs, nonKeysIntList, property2Id, id2Property, propertiesList, chunk[0],
                            chunk[1], output);
                }

            }
        });
        threads[i].start();
    }

    for (int i = 0; i < threads.length; ++i) {
        threads[i].join();
    }
    long timeb = System.currentTimeMillis();
    System.out.println("==== Unique C-keys =====");
    for (Rule r : output) {
        System.out.println(Utilities.formatKey(r));
    }
    System.out.println(
            "VICKEY found " + output.size() + " unique conditional keys in " + (timeb - timea) + " ms");
}

From source file:org.apache.streams.util.ComponentUtils.java

/**
 * Certain types of queues will return null when calling {@link java.util.Queue#poll()} due to many factors depending
 * on the type of queue.  <code>pollWhileNotEmpty</code> will poll the queue until an item from the queue is returned
 * or the queue is empty.  If the queue is empty it will return NULL.
 * @param queue/*from  www  . j a  va2s.  c o m*/
 * @param <T>
 * @return
 */
public static <T> T pollWhileNotEmpty(Queue<T> queue) {
    T item = queue.poll();
    while (!queue.isEmpty() && item == null) {
        Thread.yield();
        item = queue.poll();
    }
    return item;
}

From source file:Main.java

/**
 * Polls every element within the specified {@link Queue} and performs the specified {@link Consumer} event for each
 * element./*ww w .  ja  v a 2 s.  c  o  m*/
 *
 * @param queue The Queue to poll each element for, may not be {@code null}.
 * @param consumer The Consumer event to execute for each polled element, may not be {@code null}.
 */
public static <T> void pollAll(Queue<T> queue, Consumer<T> consumer) {
    Preconditions.checkNotNull(queue, "Queue may not be null");
    Preconditions.checkNotNull(consumer, "Consumer may not be null");

    T element;
    while ((element = queue.poll()) != null) {
        consumer.accept(element);
    }
}