Example usage for java.util LinkedList removeFirst

List of usage examples for java.util LinkedList removeFirst

Introduction

In this page you can find the example usage for java.util LinkedList removeFirst.

Prototype

public E removeFirst() 

Source Link

Document

Removes and returns the first element from this list.

Usage

From source file:org.apache.rocketmq.example.benchmark.Producer.java

public static void main(String[] args) throws MQClientException, UnsupportedEncodingException {

    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkProducer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);//from w w  w. j a v  a 2s. com
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final int threadCount = commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 64;
    final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s'))
            : 128;
    final boolean keyEnable = commandLine.hasOption('k')
            && Boolean.parseBoolean(commandLine.getOptionValue('k'));
    final int propertySize = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 0;

    System.out.printf("topic %s threadCount %d messageSize %d keyEnable %s%n", topic, threadCount, messageSize,
            keyEnable);

    final InternalLogger log = ClientLogger.getLog();

    final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount);

    final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmark.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]);

                System.out.printf(
                        "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n",
                        sendTps, statsBenchmark.getSendMessageMaxRT().get(), averageRT, end[2], end[4]);
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer");
    producer.setInstanceName(Long.toString(System.currentTimeMillis()));

    if (commandLine.hasOption('n')) {
        String ns = commandLine.getOptionValue('n');
        producer.setNamesrvAddr(ns);
    }

    producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE);

    producer.start();

    for (int i = 0; i < threadCount; i++) {
        sendThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        final Message msg;
                        try {
                            msg = buildMessage(messageSize, topic);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            return;
                        }
                        final long beginTimestamp = System.currentTimeMillis();
                        if (keyEnable) {
                            msg.setKeys(String.valueOf(beginTimestamp / 1000));
                        }
                        if (propertySize > 0) {
                            if (msg.getProperties() != null) {
                                msg.getProperties().clear();
                            }
                            int i = 0;
                            int startValue = (new Random(System.currentTimeMillis())).nextInt(100);
                            int size = 0;
                            while (true) {
                                String prop1 = "prop" + i, prop1V = "hello" + startValue;
                                String prop2 = "prop" + (i + 1), prop2V = String.valueOf(startValue);
                                msg.putUserProperty(prop1, prop1V);
                                msg.putUserProperty(prop2, prop2V);
                                size += prop1.length() + prop2.length() + prop1V.length() + prop2V.length();
                                if (size > propertySize) {
                                    break;
                                }
                                i += 2;
                                startValue += 2;
                            }
                        }
                        producer.send(msg);
                        statsBenchmark.getSendRequestSuccessCount().incrementAndGet();
                        statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet();
                        final long currentRT = System.currentTimeMillis() - beginTimestamp;
                        statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT);
                        long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        while (currentRT > prevMaxRT) {
                            boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT,
                                    currentRT);
                            if (updated)
                                break;

                            prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        }
                    } catch (RemotingException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignored) {
                        }
                    } catch (InterruptedException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e1) {
                        }
                    } catch (MQClientException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                    } catch (MQBrokerException e) {
                        statsBenchmark.getReceiveResponseFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignored) {
                        }
                    }
                }
            }
        });
    }
}

From source file:example.Publisher.java

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

    String user = env("ACTIVEMQ_USER", "admin");
    String password = env("ACTIVEMQ_PASSWORD", "password");
    String host = env("ACTIVEMQ_HOST", "localhost");
    int port = Integer.parseInt(env("ACTIVEMQ_PORT", "1883"));
    final String destination = arg(args, 0, "/topic/event");

    int messages = 10000;
    int size = 256;

    String DATA = "abcdefghijklmnopqrstuvwxyz";
    String body = "";
    for (int i = 0; i < size; i++) {
        body += DATA.charAt(i % DATA.length());
    }/*from w  w  w . j  a  v  a2  s.  co m*/
    Buffer msg = new AsciiBuffer(body);

    MQTT mqtt = new MQTT();
    mqtt.setHost(host, port);
    mqtt.setUserName(user);
    mqtt.setPassword(password);

    FutureConnection connection = mqtt.futureConnection();
    connection.connect().await();

    final LinkedList<Future<Void>> queue = new LinkedList<Future<Void>>();
    UTF8Buffer topic = new UTF8Buffer(destination);
    for (int i = 1; i <= messages; i++) {

        // Send the publish without waiting for it to complete. This allows us
        // to send multiple message without blocking..
        queue.add(connection.publish(topic, msg, QoS.AT_LEAST_ONCE, false));

        // Eventually we start waiting for old publish futures to complete
        // so that we don't create a large in memory buffer of outgoing message.s
        if (queue.size() >= 1000) {
            queue.removeFirst().await();
        }

        if (i % 1000 == 0) {
            System.out.println(String.format("Sent %d messages.", i));
        }
    }

    queue.add(connection.publish(topic, new AsciiBuffer("SHUTDOWN"), QoS.AT_LEAST_ONCE, false));
    while (!queue.isEmpty()) {
        queue.removeFirst().await();
    }

    connection.disconnect().await();

    System.exit(0);
}

From source file:LinkedListExample.java

public static void main(String[] args) {
    // Create a new LinkedList
    LinkedList<Integer> list = new LinkedList<Integer>();

    // Add Items to the array list
    list.add(new Integer(1));
    list.add(new Integer(2));
    list.add(new Integer(3));
    list.add(new Integer(4));
    list.add(new Integer(5));
    list.add(new Integer(6));
    list.add(new Integer(7));
    list.add(new Integer(8));
    list.add(new Integer(9));
    list.add(new Integer(10));

    // Use iterator to display the values
    for (Iterator i = list.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }// w w w . j  a v a 2 s  . c o  m

    // Remove the element at index 5 (value=6)
    list.remove(5);

    // Set the value at index 5, this overwrites the value 7
    list.set(5, new Integer(66));

    // Use the linked list as a queue:
    // add an object to the end of the list (queue)
    // remove an item from the head of the list (queue)
    list.addLast(new Integer(11));
    Integer head = (Integer) list.removeFirst();
    System.out.println("Head: " + head);

    // Use iterator to display the values
    for (Iterator i = list.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }
}

From source file:org.zoneproject.extractor.plugin.spotlight.App.java

public static void main(String[] args) {
    LinkedList<Item> itemsPending = new LinkedList<Item>();
    Prop[] fr = { new Prop(ZoneOntology.PLUGIN_LANG, "\"fr\"") };
    Prop[] en = { new Prop(ZoneOntology.PLUGIN_LANG, "\"en\"") };

    LinkedBlockingQueue<AnnotationThread> annotationThreads;
    HashMap<String, ArrayList<Prop>> propsToSave;
    propsPendingSave = new HashMap<String, ArrayList<Prop>>();
    while (true) {
        annotationThreads = new LinkedBlockingQueue<AnnotationThread>();

        while (true) {//while we can download items

            Item[] enItems = Database.getItemsNotAnotatedForPluginsWithDeps(PLUGIN_URI, en, SIM_DOWNLOADS / 2);
            Item[] frItems = Database.getItemsNotAnotatedForPluginsWithDeps(PLUGIN_URI, fr, SIM_DOWNLOADS / 2);
            Item[] items = (Item[]) ArrayUtils.addAll(enItems, frItems);

            if (items != null && items.length > 0) {
                //check if the item is in annotation process
                for (Item i : items) {
                    boolean exist = false;
                    for (AnnotationThread a : annotationThreads) {
                        if (a.item.getUri().equals(i.getUri())) {
                            exist = true;
                        }//  w w w . j  av a2s.c  o m
                    }
                    if (!exist) {
                        itemsPending.add(i);
                    }
                }
            }
            if (itemsPending.isEmpty()) {
                break;
            }

            while (!itemsPending.isEmpty()) {

                //we add new thread until the limit length is thrown
                while (annotationThreads.size() < SIM_ANNOTATE && !itemsPending.isEmpty()) {
                    AnnotationThread newAnnot = new AnnotationThread(itemsPending.removeFirst());
                    newAnnot.start();
                    annotationThreads.add(newAnnot);
                }

                //try{
                //we try to end some terminated threads
                //synchronized(annotationThreads){
                for (AnnotationThread a : annotationThreads) {
                    if (!a.isAlive()) {
                        annotationThreads.remove(a);
                    } else if (a.getDuration() > LIMIT_TIME_FOR_DOWN) {
                        a.interrupt();
                    } else if (a.getDuration() > 10) {
                        logger.info("is alive[" + a.getDuration() + "]: " + a.item.getUri());
                    }
                    //try{Thread.currentThread().sleep(1000);}catch(Exception ie){}//TODO remove
                }
                //}
                //}catch(java.util.ConcurrentModificationException concurrentAccess){
                //    logger.warn("concurrent access!");
                //}

                if (annotationThreads.size() >= SIM_ANNOTATE) {
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (Exception ie) {
                    }
                }
            }

            logger.info("start saving");
            synchronized (propsPendingSave) {
                propsToSave = (HashMap<String, ArrayList<Prop>>) propsPendingSave.clone();
                propsPendingSave.clear();
            }
            Database.addAnnotations(propsToSave);
            logger.info("end saving");

        }

        logger.info("no more items to annotate");
        try {
            Thread.currentThread().sleep(1000);
        } catch (Exception ie) {
        }
    }
}

From source file:org.nuxeo.ecm.platform.sync.utils.ImportUtils.java

/**
 * Returns the list of transition names to follow to go from one particular state to another.
 *
 * @param lifeCycle - the lifecycle//from  w ww.  j  ava2 s .  c  o  m
 * @param origState - the origin state
 * @param destState - the destination state
 * @return the list of transition names
 */
public static List<String> getLifeCycleTransitions(LifeCycle lifeCycle, String origState, String destState)
        throws LifeCycleException {
    List<String> path = new ArrayList<String>();
    LinkedList<List<String>> paths = new LinkedList<List<String>>();
    paths.add(path);

    LinkedList<String> fifo = new LinkedList<String>();
    fifo.add(origState);

    ArrayList<String> marked = new ArrayList<String>();
    marked.add(origState);

    while (!fifo.isEmpty()) {
        String state = fifo.removeFirst();
        path = paths.removeFirst();
        if (state.equals(destState)) {
            break;
        }
        for (String transitionName : lifeCycle.getAllowedStateTransitionsFrom(state)) {
            LifeCycleTransition transition = lifeCycle.getTransitionByName(transitionName);
            String nextState = transition.getDestinationStateName();
            if (!marked.contains(nextState)) {
                marked.add(nextState);
                fifo.addLast(nextState);
                List<String> nextPath = new ArrayList<String>(path);
                nextPath.add(transitionName);
                paths.addLast(nextPath);
            }
        }
    }

    return path;
}

From source file:org.diorite.config.impl.NestedNodesHelper.java

@Nullable
@SuppressWarnings("unchecked")
static Object remove(Object object, LinkedList<String> path) {
    while (true) {
        if (path.isEmpty()) {
            throw new IllegalArgumentException("Empty path given");
        }//from   w ww  .j a v  a 2 s  .  c  o  m
        String current = path.removeFirst();
        try {
            Object val;
            if (object instanceof Config) {
                val = ((Config) object).remove(current);
            } else if (object instanceof Map) {
                val = ((Map<Object, Object>) object).remove(current);
            } else if (object instanceof List) {
                val = ((List<Object>) object).remove(Integer.parseInt(current));
            } else {
                throw new IllegalStateException("Can't remove class property!");
            }
            if (path.isEmpty()) {
                return val;
            }
            Validate.notNull(val, "Value on: " + current + " in " + object + " is null");
            object = val;
        } catch (Exception e) {
            throw new IllegalStateException("Can't find property: " + current + " (" + path + ") in: " + object,
                    e);
        }
    }
}

From source file:org.diorite.config.impl.NestedNodesHelper.java

@SuppressWarnings("unchecked")
@Nullable//from  w  ww . j a  v  a 2s.  c  o m
static Object get(Object object, LinkedList<String> path) {
    while (true) {
        if (path.isEmpty()) {
            throw new IllegalArgumentException("Empty path given");
        }
        String current = path.removeFirst();
        try {
            Object val;
            if (object instanceof Config) {
                val = ((Config) object).get(current);
            } else if (object instanceof Map) {
                val = ((Map<Object, Object>) object).get(current);
            } else if (object instanceof List) {
                val = ((List<Object>) object).get(Integer.parseInt(current));
            } else {
                Class<?> type = object.getClass();
                CacheKey cacheKey = new CacheKey(type, current);
                ReflectedProperty<?> property = propertyCache.computeIfAbsent(cacheKey,
                        k -> DioriteReflectionUtils.getReflectedProperty(current, type));
                val = property.get(object);
            }
            if (path.isEmpty()) {
                return val;
            }
            Validate.notNull(val, "Value on: " + current + " in " + object + " is null");
            object = val;
        } catch (Exception e) {
            throw new IllegalStateException("Can't find property: " + current + " (" + path + ") in: " + object,
                    e);
        }
    }
}

From source file:org.trend.hgraph.util.FindCandidateEntities.java

private static boolean doBreadthFirstSearch(Graph g, String id, long mn, SearchStrategy s) throws IOException {
    boolean yes = false;
    Vertex v = g.getVertex(id);/* www  .jav  a 2s .  c om*/
    long cn = 0L;
    String hashCode = null;
    Set<String> set = new HashSet<String>();
    if (null != v) {
        LinkedList<Vertex> queue = new LinkedList<Vertex>();
        queue.add(v);
        while (queue.size() > 0) {
            v = queue.removeFirst();
            hashCode = SecurityUtils.encrypt(v.getId() + "", "SHA");
            if (!set.contains(hashCode)) {
                set.add(hashCode);
                cn++;
                s.processV(v);
                if (cn == mn) {
                    yes = true;
                    break;
                }
                for (Edge e : v.getEdges()) {
                    s.processE(e);
                    queue.add((Vertex) e.getVertex(Direction.OUT));
                }
            }
        }
    }
    return yes;
}

From source file:Main.java

public static int deepHashCode(Object obj) {
    Set visited = new HashSet();
    LinkedList<Object> stack = new LinkedList<Object>();
    stack.addFirst(obj);//from   w w w  .j av  a2s  . com
    int hash = 0;

    while (!stack.isEmpty()) {
        obj = stack.removeFirst();
        if (obj == null || visited.contains(obj)) {
            continue;
        }

        visited.add(obj);

        if (obj.getClass().isArray()) {
            int len = Array.getLength(obj);
            for (int i = 0; i < len; i++) {
                stack.addFirst(Array.get(obj, i));
            }
            continue;
        }

        if (obj instanceof Collection) {
            stack.addAll(0, (Collection) obj);
            continue;
        }

        if (obj instanceof Map) {
            stack.addAll(0, ((Map) obj).keySet());
            stack.addAll(0, ((Map) obj).values());
            continue;
        }

        if (hasCustomHashCode(obj.getClass())) {
            hash += obj.hashCode();
            continue;
        }

        Collection<Field> fields = getDeepDeclaredFields(obj.getClass());
        for (Field field : fields) {
            try {
                stack.addFirst(field.get(obj));
            } catch (Exception ignored) {
            }
        }
    }
    return hash;
}

From source file:de.hasait.clap.impl.CLAPClassNode.java

private static <A extends Annotation> A findAnnotation(final Class<?> pClass, final Class<A> pAnnotationClass) {
    final LinkedList<Class<?>> queue = new LinkedList<Class<?>>();
    queue.add(pClass);//w w w  .  j  a  va 2  s.co  m
    while (!queue.isEmpty()) {
        final Class<?> clazz = queue.removeFirst();
        if (clazz != null) {
            final A result = clazz.getAnnotation(pAnnotationClass);
            if (result != null) {
                return result;
            }
            queue.add(clazz.getSuperclass());
            for (final Class<?> interfaze : clazz.getInterfaces()) {
                queue.add(interfaze);
            }
        }
    }
    return null;
}