Example usage for java.util Queue isEmpty

List of usage examples for java.util Queue isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:com.ok2c.lightmtp.examples.MailUserAgentExample.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";

    List<DeliveryRequest> requests = new ArrayList<DeliveryRequest>();
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII"))));
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII"))));
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII"))));

    MailUserAgent mua = new DefaultMailUserAgent(TransportType.SMTP, IOReactorConfig.DEFAULT);
    mua.start();/*from  w  w w.  java2 s. c o  m*/

    try {

        InetSocketAddress address = new InetSocketAddress("localhost", 2525);

        Queue<Future<DeliveryResult>> queue = new LinkedList<Future<DeliveryResult>>();
        for (DeliveryRequest request : requests) {
            queue.add(mua.deliver(new SessionEndpoint(address), 0, request, null));
        }

        while (!queue.isEmpty()) {
            Future<DeliveryResult> future = queue.remove();
            DeliveryResult result = future.get();
            System.out.println("Delivery result: " + result);
        }

    } finally {
        mua.shutdown();
    }
}

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   w w  w  .j a  v  a  2  s.co 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:io.aos.protocol.http.httpcommon.FluentAsync.java

public static void main(String... args) throws Exception {
    // Use pool of two threads
    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);

    Request[] requests = new Request[] { Request.Get("http://www.google.com/"),
            Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"),
            Request.Get("http://www.apple.com/") };

    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request : requests) {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            public void failed(final Exception ex) {
                System.out.println(ex.getMessage() + ": " + request);
            }//from   w  w  w .  jav  a 2 s.  c om

            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
            }

            public void cancelled() {
            }

        });
        queue.add(future);
    }

    while (!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {
            future.get();
        } catch (ExecutionException ex) {
        }
    }
    System.out.println("Done");
    threadpool.shutdown();
}

From source file:interoperabilite.webservice.fluent.FluentAsync.java

public static void main(String[] args) throws Exception {
    // Use pool of two threads
    ExecutorService threadpool = Executors.newFixedThreadPool(2);
    Async async = Async.newInstance().use(threadpool);

    Request[] requests = new Request[] { Request.Get("http://www.google.com/"),
            Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"),
            Request.Get("http://www.apple.com/") };

    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request : requests) {
        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            @Override//from  w  w w. j a  va  2 s. co m
            public void failed(final Exception ex) {
                System.out.println(ex.getMessage() + ": " + request);
            }

            @Override
            public void completed(final Content content) {
                System.out.println("Request completed: " + request);
            }

            @Override
            public void cancelled() {
            }

        });
        queue.add(future);
    }

    while (!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {
            future.get();
        } catch (ExecutionException ex) {
        }
    }
    System.out.println("Done");
    threadpool.shutdown();
}

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 .ja 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:Main.java

public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> aClazz) {
    //Check class hierarchy
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        T anno = c.getAnnotation(aClazz);
        if (anno != null) {
            return anno;
        }/*w w w  . ja  v  a2 s  . co m*/
    }

    //Check interfaces (breadth first)
    Queue<Class<?>> q = new LinkedList<Class<?>>();
    q.add(clazz);
    while (!q.isEmpty()) {
        Class<?> c = q.remove();
        if (c != null) {
            if (c.isInterface()) {
                T anno = c.getAnnotation(aClazz);
                if (anno != null) {
                    return anno;
                }
            } else {
                q.add(c.getSuperclass());
            }
            q.addAll(Arrays.asList(c.getInterfaces()));
        }
    }

    return null;
}

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// ww  w.j a v a2  s.co  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

/**
 * 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.
 * //from w  w  w . ja  v  a2 s .  com
 * @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:graphs.Graphs.java

public static <V, E> String BreadthSearch(Graph<V, E> g) {
    StringBuilder b = new StringBuilder();

    Queue<V> Qu = new LinkedList<V>();
    Set<V> visited = new HashSet();
    Set<V> found = new HashSet();

    V start = (V) g.getVertices().toArray()[0];
    Qu.add(start);/*from w ww  . j a v a2  s .c  om*/
    found.add(start);

    while (!Qu.isEmpty()) {
        V vertex = Qu.remove();
        for (V neighbor : g.getNeighbors(vertex)) {
            if (!found.contains(neighbor) && !visited.contains(neighbor)) {
                found.add(neighbor);
                Qu.add(neighbor);
            }
        }
        b.append(vertex.toString() + " ");
        visited.add(vertex);
    }

    return b.toString();
}

From source file:fr.inria.atlanmod.emf.graphs.Connectedness.java

/**
 * Returns the {@link Set} of {@link EObject}s that can be reached by
 * navigating {@link EReference}s, starting from <code>initialEObject</code>
 * /*from www .  ja v a 2s.c om*/
 * @param initialEObject
 *            The initial {@link EObject}
 * @return The {@link Set} of reachable {@link EObject}s
 */
private static Set<EObject> getReachableEObjects(EObject initialEObject) {
    Set<EObject> visited = new HashSet<>();
    Queue<EObject> next = new LinkedList<EObject>();
    next.add(initialEObject);

    while (!next.isEmpty()) {
        EObject activeEObject = next.poll();
        if (visited.add(activeEObject)) {
            next.addAll(activeEObject.eContents());
            next.addAll(activeEObject.eCrossReferences());
        }
    }

    return visited;
}