Example usage for java.util Queue size

List of usage examples for java.util Queue size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this collection.

Usage

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;/*  ww  w .j a  va 2  s  .  c  o m*/
    while ((data = queue.poll()) != null) {
        System.out.println(data);
    }
}

From source file:com.ok2c.lightmtp.examples.LocalMailClientTransportExample.java

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

    String text1 = "From: root\r\n" + "To: testuser1\r\n" + "Subject: test message 1\r\n" + "\r\n"
            + "This is a short test message 1\r\n";
    String text2 = "From: root\r\n" + "To: testuser1, testuser2\r\n" + "Subject: test message 2\r\n" + "\r\n"
            + "This is a short test message 2\r\n";
    String text3 = "From: root\r\n" + "To: testuser1, testuser2, testuser3\r\n" + "Subject: test message 3\r\n"
            + "\r\n" + "This is a short test message 3\r\n";

    DeliveryRequest request1 = new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII")));

    DeliveryRequest request2 = new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII")));

    DeliveryRequest request3 = new BasicDeliveryRequest("root",
            Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII")));

    Queue<DeliveryRequest> queue = new ConcurrentLinkedQueue<DeliveryRequest>();
    queue.add(request1);//from  w  w  w  . java2  s  .com
    queue.add(request2);
    queue.add(request3);

    CountDownLatch messageCount = new CountDownLatch(queue.size());

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    MailClientTransport mua = new LocalMailClientTransport(config);
    mua.start(new MyDeliveryRequestHandler(messageCount));

    SessionEndpoint endpoint = new SessionEndpoint(new InetSocketAddress("localhost", 2525));

    SessionRequest sessionRequest = mua.connect(endpoint, queue, null);
    sessionRequest.waitFor();

    IOSession iosession = sessionRequest.getSession();
    if (iosession != null) {
        messageCount.await();
    } else {
        IOException ex = sessionRequest.getException();
        if (ex != null) {
            System.out.println("Connection failed: " + ex.getMessage());
        }
    }

    System.out.println("Shutting down I/O reactor");
    try {
        mua.shutdown();
    } catch (IOException ex) {
        mua.forceShutdown();
    }
    System.out.println("Done");
}

From source file:poisondog.demo.StringDemo.java

public static void main(String[] args) {
    //      String temp=" command  para1 para2  ";
    //      System.out.println(temp.replaceAll("^\\s*\\S*\\s*", "").replaceAll("\\s*$", "") + "]]");

    Queue<Double> queue = new CircularFifoQueue<Double>(1000);
    List<Double> all = new LinkedList<Double>();
    List<Double> list = new ArrayList<Double>();
    double result = 0;
    double sum = 0;
    Random r = new Random();
    for (int i = 0; i < 10000; i++) {
        double g = r.nextGaussian() * 100 - 5;
        sum += g;//w ww . ja  v a2  s  .co  m
        if (g > 0)
            result++;
        if (i > 5000 && getRate(queue) < getRate(all) * .94)
            list.add(g);
        all.add(g);
        queue.add(g);
        //         if (queue.size() > 1000)
        //            queue.remove();

    }
    //      System.out.println(list.size());
    int count = 0;
    for (Double d : list) {
        if (d > 0)
            count++;
    }
    System.out.println("Origin Rate: " + (double) result / all.size());
    System.out.println("Origin Sum: " + sum);
    System.out.println("Upgrade Rate: " + (double) count / list.size());
    System.out.println("Upgrade Count: " + list.size());
    System.out.println("Upgrade Sum: " + getSum(list));
    System.out.println("Queue Count: " + queue.size());
}

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   ww w. j  a va  2 s  .  c  o  m*/
        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 ww  .  j  ava 2  s  . co  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:Main.java

/**
 * Creates a list by pulling off the head of a queue one item at a time and
 * adding it to an output list. The input queue is emptied by this method.
 * /* www  . j  a v  a2 s  . c  o  m*/
 * @param <T>
 * @param queue
 * @param outputList
 * @param reverse
 *            whether or not to reverse the resulting list
 * @return
 */
public static <T> List<T> createList(Queue<T> queue, List<T> outputList, boolean reverse) {
    if (outputList == null) {
        outputList = new ArrayList<T>(queue.size());
    }
    while (!queue.isEmpty()) {
        outputList.add(queue.poll());
    }
    if (reverse) {
        Collections.reverse(outputList);
    }
    return outputList;
}

From source file:org.apache.mahout.clustering.lda.LDAPrintTopics.java

private static void maybeEnqueue(Queue<Pair<String, Double>> q, String word, double score,
        int numWordsToPrint) {
    if (q.size() >= numWordsToPrint && score > q.peek().getSecond()) {
        q.poll();//from   w ww .  j  a v  a 2 s  .  c o  m
    }
    if (q.size() < numWordsToPrint) {
        q.add(new Pair<String, Double>(word, score));
    }
}

From source file:org.apache.mahout.clustering.lda.LDAPrintTopics.java

private static List<Queue<Pair<String, Double>>> topWordsForTopics(String dir, Configuration job,
        List<String> wordList, int numWordsToPrint) {
    List<Queue<Pair<String, Double>>> queues = Lists.newArrayList();
    Map<Integer, Double> expSums = Maps.newHashMap();
    for (Pair<IntPairWritable, DoubleWritable> record : new SequenceFileDirIterable<IntPairWritable, DoubleWritable>(
            new Path(dir, "part-*"), PathType.GLOB, null, null, true, job)) {
        IntPairWritable key = record.getFirst();
        int topic = key.getFirst();
        int word = key.getSecond();
        ensureQueueSize(queues, topic);//w  w  w.ja  v  a2s .  c o m
        if (word >= 0 && topic >= 0) {
            double score = record.getSecond().get();
            if (expSums.get(topic) == null) {
                expSums.put(topic, 0.0);
            }
            expSums.put(topic, expSums.get(topic) + Math.exp(score));
            String realWord = wordList.get(word);
            maybeEnqueue(queues.get(topic), realWord, score, numWordsToPrint);
        }
    }
    for (int i = 0; i < queues.size(); i++) {
        Queue<Pair<String, Double>> queue = queues.get(i);
        Queue<Pair<String, Double>> newQueue = new PriorityQueue<Pair<String, Double>>(queue.size());
        double norm = expSums.get(i);
        for (Pair<String, Double> pair : queue) {
            newQueue.add(new Pair<String, Double>(pair.getFirst(), Math.exp(pair.getSecond()) / norm));
        }
        queues.set(i, newQueue);
    }
    return queues;
}

From source file:org.jspringbot.keyword.expression.ELUtils.java

public static Object doCase(Object... args) {
    Object defaultValue = null;//from  w  w w  .  j a  v  a 2  s  .  com

    Queue<Object> arguments = new LinkedList<Object>();
    arguments.addAll(Arrays.asList(args));

    while (!arguments.isEmpty()) {
        if (arguments.size() > 1) {
            boolean condition = (Boolean) arguments.remove();
            Object value = arguments.remove();
            if (condition) {
                return value;
            }
        } else {
            // default
            return arguments.remove();
        }
    }

    return defaultValue;
}

From source file:org.jspringbot.keyword.expression.ELUtils.java

public static Object doMap(Object... args) {
    Object defaultValue = null;//w w w.  ja  v a 2 s . c  om

    Queue<Object> arguments = new LinkedList<Object>();
    arguments.addAll(Arrays.asList(args));

    Object variable = arguments.remove();

    while (!arguments.isEmpty()) {
        if (arguments.size() > 1) {
            Object variableValue = arguments.remove();
            Object mapValue = arguments.remove();
            if (variable.equals(variableValue)) {
                return mapValue;
            }
        } else {
            // default
            return arguments.remove();
        }
    }

    return defaultValue;
}