Example usage for java.util LinkedList getLast

List of usage examples for java.util LinkedList getLast

Introduction

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

Prototype

public E getLast() 

Source Link

Document

Returns the last element in this list.

Usage

From source file:MainClass.java

public static void main(String[] a) {

    LinkedList list = new LinkedList();

    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.addFirst("X");
    list.addLast("Z");

    System.out.println(list);// w w  w  .j  a v a  2 s  .c  o m
    System.out.println(list.getFirst());
    System.out.println(list.getLast());
}

From source file:MainClass.java

public static void main(String[] a) {

    LinkedList list = new LinkedList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.addFirst("X");
    list.addLast("Z");

    System.out.println(list);//from  w  w w .  j a va  2  s .c  o  m
    System.out.println(list.getFirst());
    System.out.println(list.getLast());

    list.removeFirst();
    list.removeLast();

    System.out.println(list);
}

From source file:Main.java

public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");

    System.out.println("First element of LinkedList is : " + lList.getFirst());
    System.out.println("Last element of LinkedList is : " + lList.getLast());
}

From source file:Main.java

public static void main(String[] args) {

    // create a LinkedList
    LinkedList<String> list = new LinkedList<String>();

    // add some elements
    list.add("Hello");
    list.add("from java2s.com");
    list.add("10");

    // print the list
    System.out.println("LinkedList:" + list);

    // print the last element of the list
    System.out.println("Last Element :" + list.getLast());
}

From source file:org.dbpedia.spotlight.evaluation.SpotterMemoryEvaluator.java

public static void main(String[] args) throws IOException, JSONException, ConfigurationException,
        InitializationException, org.json.JSONException, SpottingException {

    File dictionary = new File(
            "/Users/jodaiber/Desktop/lrec_2012_spotting/surface_forms-Wikipedia-TitRedDis.thresh3.spotterDictionary");

    Spotter spotter = null;//  w w  w  . j a  v a2 s .c o  m

    //
    if (args.length == 0) {
        LOG.error("server.properties is requested to continue...");
        return;
    }

    SpotlightConfiguration configuration = new SpotlightConfiguration(args[0]);

    int spotterNr = 0;

    switch (spotterNr) {
    case 0: {
        String openNLPDir = "/Users/jodaiber/Desktop/DBpedia/";
        SurfaceFormDictionary sfDictProbThresh3 = ExactSurfaceFormDictionary.fromLingPipeDictionary(dictionary,
                false);
        System.out.println("Dictionary size: " + sfDictProbThresh3.size());
        File stopwordsFile = new File(openNLPDir + "stopwords.txt");
        spotter = OpenNLPChunkerSpotter.fromDir(openNLPDir, configuration.getI18nLanguageCode(),
                sfDictProbThresh3, stopwordsFile);
        break;
    }
    case 1: {
        spotter = new LingPipeSpotter(dictionary, configuration.getAnalyzer());
        break;
    }
    }

    System.out.println("Using Spotter " + spotter.getName());

    System.out.println("Running GC.");
    System.gc();
    System.gc();
    System.gc();
    System.gc();

    int i = 0;

    LinkedList<Long> consumption = new LinkedList<Long>();

    for (File textFile : new File("/data/spotlight/csaw/original/crawledDocs").listFiles()) {

        if (!textFile.getName().endsWith(".txt"))
            continue;

        i++;
        if (i == 100)
            break;

        spotter.extract(new Text(new Scanner(textFile).useDelimiter("\\A").next()));

        consumption.addLast(
                (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024));
        System.out.println("Memory consumption: " + consumption.getLast());
    }

    long total = 0;
    for (long step : consumption) {
        total += step;
    }

    System.out.println("Mean consumption: " + (total / consumption.size()));

}

From source file:com.alibaba.rocketmq.example.benchmark.Consumer.java

public static void main(String[] args) throws MQClientException {
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);/*from  w ww. ja  va2 s  .c  om*/
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim()
            : "benchmark_consumer";
    final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true";
    String group = groupPrefix;
    if (Boolean.parseBoolean(isPrefixEnable)) {
        group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100);
    }

    System.out.printf("topic %s group %s prefix %s%n", topic, group, isPrefixEnable);

    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

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

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

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.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 consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]);
                final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]);

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n",
                        consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]);
            }
        }

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

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe(topic, "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.printf("Consumer Started.%n");
}

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

public static void main(String[] args) throws MQClientException, IOException {
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);/*  ww  w.ja v  a2  s . com*/
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim()
            : "benchmark_consumer";
    final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true";
    final String filterType = commandLine.hasOption('f') ? commandLine.getOptionValue('f').trim() : null;
    final String expression = commandLine.hasOption('e') ? commandLine.getOptionValue('e').trim() : null;
    String group = groupPrefix;
    if (Boolean.parseBoolean(isPrefixEnable)) {
        group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100);
    }

    System.out.printf("topic: %s, group: %s, prefix: %s, filterType: %s, expression: %s%n", topic, group,
            isPrefixEnable, filterType, expression);

    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

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

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

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.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 consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]);
                final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]);

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n",
                        consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]);
            }
        }

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

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    if (filterType == null || expression == null) {
        consumer.subscribe(topic, "*");
    } else {
        if (ExpressionType.TAG.equals(filterType)) {
            String expr = MixAll.file2String(expression);
            System.out.printf("Expression: %s%n", expr);
            consumer.subscribe(topic, MessageSelector.byTag(expr));
        } else if (ExpressionType.SQL92.equals(filterType)) {
            String expr = MixAll.file2String(expression);
            System.out.printf("Expression: %s%n", expr);
            consumer.subscribe(topic, MessageSelector.bySql(expr));
        } else {
            throw new IllegalArgumentException("Not support filter type! " + filterType);
        }
    }

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.printf("Consumer Started.%n");
}

From source file:com.damon.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 ww  w  . j  a  va 2  s .c o m*/
    }

    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'));

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

    final Logger log = ClientLogger.getLog();

    final Message msg = buildMessage(messageSize, topic);

    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 long beginTimestamp = System.currentTimeMillis();
                        if (keyEnable) {
                            msg.setKeys(String.valueOf(beginTimestamp / 1000));
                        }
                        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:com.alibaba.rocketmq.example.benchmark.Producer.java

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

    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("producer", args, buildCommandlineOptions(options),
            new PosixParser());
    if (null == commandLine) {
        System.exit(-1);/* ww  w .j av  a 2s .c  o  m*/
    }

    final int threadCount = commandLine.hasOption('t') ? Integer.parseInt(commandLine.getOptionValue('t')) : 64;
    final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s'))
            : 128;
    final boolean keyEnable = commandLine.hasOption('k') ? Boolean.parseBoolean(commandLine.getOptionValue('k'))
            : false;

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

    final Logger log = ClientLogger.getLog();

    final Message msg = buildMessage(messageSize);

    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 long beginTimestamp = System.currentTimeMillis();
                        if (keyEnable) {
                            msg.setKeys(String.valueOf(beginTimestamp / 1000));
                        }
                        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 e1) {
                        }
                    } 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 e1) {
                        }
                    }
                }
            }
        });
    }
}

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  av  a2 s.c o  m*/
    }

    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) {
                        }
                    }
                }
            }
        });
    }
}