Example usage for java.util.concurrent ScheduledExecutorService shutdown

List of usage examples for java.util.concurrent ScheduledExecutorService shutdown

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledExecutorService shutdown.

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:com.mch.registry.ccs.server.CcsClient.java

/**
 * Sends messages to registered devices/*www  . j  a va  2  s .  com*/
 */
public static void main(String[] args) {

    Config config = new Config();
    final String projectId = config.getProjectId();
    final String key = config.getKey();

    final CcsClient ccsClient = CcsClient.prepareClient(projectId, key, true);

    try {
        ccsClient.connect();
    } catch (XMPPException e) {
        logger.log(Level.WARNING, "XMPP Exception ", e);
    }

    final Runnable sendNotifications = new Runnable() {
        public void run() {
            try {
                logger.log(Level.INFO, "Working Q!");
                if (!isOffHours()) {
                    //Prepare downstream message
                    String toRegId = "";
                    String message = "";
                    String messageId = "";
                    Map<String, String> payload = new HashMap<String, String>();
                    String collapseKey = null;
                    Long timeToLive = 10000L;
                    Boolean delayWhileIdle = true;
                    String messagePrefix = "";
                    int notificationQueueID = 0;
                    boolean sucessfullySent = false;

                    //Read from mysql database
                    MySqlHandler mysql = new MySqlHandler();
                    ArrayList<Notification> queue = new ArrayList<Notification>();

                    for (int i = 1; i < 3; i++) {
                        queue = mysql.getNotificationQueue(i);
                        if (queue.size() > 0) {

                            switch (i) {
                            case 1:
                                messagePrefix = "_V: ";
                                break;
                            case 2:
                                messagePrefix = "_R: ";
                                break;
                            default:
                                messagePrefix = "";
                                logger.log(Level.WARNING, "Unknown message type!");
                            }

                            Notification notification = new Notification();
                            Iterator<Notification> iterator = queue.iterator();

                            while (iterator.hasNext()) {
                                notification = iterator.next();

                                toRegId = notification.getGcmRegID();
                                message = notification.getNotificationText();
                                notificationQueueID = notification.getNotificationQueueID();
                                messageId = "m-" + Long.toString(random.nextLong());

                                payload = new HashMap<String, String>();
                                payload.put("message", messagePrefix + message);

                                try {
                                    // Send the downstream message to a device.
                                    ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey,
                                            timeToLive, delayWhileIdle));
                                    sucessfullySent = true;
                                    logger.log(Level.INFO, "Message sent. ID: " + notificationQueueID
                                            + ", RegID: " + toRegId + ", Text: " + message);
                                } catch (Exception e) {
                                    mysql.prepareNotificationForTheNextDay(notificationQueueID);
                                    sucessfullySent = false;
                                    logger.log(Level.WARNING,
                                            "Message could not be sent! ID: " + notificationQueueID
                                                    + ", RegID: " + toRegId + ", Text: " + message);
                                }

                                if (sucessfullySent) {
                                    mysql.moveNotificationToHistory(notificationQueueID);
                                }
                            }
                        } else {
                            logger.log(Level.INFO, "No notifications to send. Type: " + Integer.toString(i));
                        }
                    }
                }
            } catch (Exception e) {
                logger.log(Level.WARNING, "Exception ", e);
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    //Start when server starts and every 30 minutes after
    ScheduledFuture task = executor.scheduleAtFixedRate(sendNotifications, 0, 30, TimeUnit.MINUTES);
    try {
        task.get();
    } catch (ExecutionException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    }
    task.cancel(false);

    try {
        executor.shutdown();
        executor.awaitTermination(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    }

}

From source file:org.openscada.hds.test.HDSApplication5.java

public static void main(final String[] args) throws Exception {
    final File base = new File("base", "data1");

    FileUtils.deleteDirectory(base.getParentFile());
    base.mkdirs();/* w w w  .  j a v a2s  . c o m*/

    final DataFilePool pool = new DataFilePool(10000);

    final File file1 = new File(base, "f1");

    {
        final DataFileAccessorImpl accessor = DataFileAccessorImpl.create(file1, new Date(), new Date());
        accessor.dispose();
    }

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);
        accessor1.dispose();
        System.out.println("Try 1");
    }

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);
        accessor1.dispose();
        System.out.println("Try 2");
    }

    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);

        try {
            System.out.println("Try 3 - 1");

            executorService.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Dispose 1");
                    accessor1.dispose();
                    System.out.println("Disposed 1");
                }
            }, 3000, TimeUnit.MILLISECONDS);

            final DataFileAccessor accessor2 = pool.getAccessor(file1);

            if (accessor2 != null) {
                System.out.println("Finally received");
                accessor2.dispose();
            }
        } finally {
            accessor1.dispose();
        }
        System.out.println("Try 3 - 2");

        accessor1.dispose();
    }

    {
        final DataFileAccessor accessor1 = pool.getAccessor(file1);
        accessor1.dispose();
        System.out.println("Try 4");
    }

    pool.dispose();

    executorService.shutdown();
}

From source file:org.dcm4che.tool.ihe.modality.Modality.java

@SuppressWarnings({ "unchecked" })
public static void main(String[] args) {
    try {//w  w  w .j  a  v a 2 s  . c o m
        CommandLine cl = parseComandLine(args);
        if (cl.getArgList().isEmpty())
            throw new MissingOptionException(rb.getString("missing-i-file"));
        final Device device = new Device("modality");
        final Connection conn = new Connection();
        final ApplicationEntity ae = new ApplicationEntity("MODALITY");
        checkOptions(cl);
        CLIUtils.configureBind(conn, ae, cl);
        CLIUtils.configure(conn, cl);
        device.addConnection(conn);
        device.addApplicationEntity(ae);
        ae.addConnection(conn);
        final MppsSCU mppsscu = new MppsSCU(ae);
        final StoreSCU storescu = new StoreSCU(ae);
        final StgCmtSCU stgcmtscu = new StgCmtSCU(ae);
        CLIUtils.configureConnect(mppsscu.getRemoteConnection(), mppsscu.getAAssociateRQ(), cl);
        CLIUtils.configureConnect(stgcmtscu.getRemoteConnection(), stgcmtscu.getAAssociateRQ(), cl);
        CLIUtils.configureConnect(storescu.getRemoteConnection(), storescu.getAAssociateRQ(), cl);
        calledAET = storescu.getAAssociateRQ().getCalledAET();
        mppsscu.setTransferSyntaxes(CLIUtils.transferSyntaxesOf(cl));
        mppsscu.setCodes(
                CLIUtils.loadProperties(cl.getOptionValue("code-config", "resource:code.properties"), null));
        if (cl.hasOption("dc"))
            mppsscu.setFinalStatus("DISCONTINUED");
        if (cl.hasOption("dc-reason"))
            mppsscu.setDiscontinuationReason(cl.getOptionValue("dc-reason"));
        stgcmtscu.setTransferSyntaxes(CLIUtils.transferSyntaxesOf(cl));
        stgcmtscu.setStorageDirectory(StgCmtSCU.getStorageDirectory(cl));
        StoreSCU.configureRelatedSOPClass(storescu, cl);
        storescu.setUIDSuffix(StoreSCU.uidSuffixOf(cl));
        Attributes attrs = new Attributes();
        CLIUtils.addAttributes(attrs, cl.getOptionValues("s"));
        mppsscu.setAttributes(attrs);
        storescu.setAttributes(attrs);
        stgcmtscu.setAttributes(attrs);
        setTlsParams(mppsscu.getRemoteConnection(), conn);
        setTlsParams(storescu.getRemoteConnection(), conn);
        setTlsParams(stgcmtscu.getRemoteConnection(), conn);
        String tmpPrefix = "iocmtest-";
        String tmpSuffix = null;
        File tmpDir = null;
        configureTmpFile(storescu, tmpPrefix, tmpSuffix, tmpDir, cl);
        String mppsiuid = UIDUtils.createUID();
        mppsscu.setPPSUID(mppsiuid);
        if (cl.hasOption("kos-title")) {
            List<String> fname = Arrays.asList(mkkos(cl));
            scanFiles(fname, tmpPrefix, tmpSuffix, tmpDir, mppsscu, storescu, stgcmtscu);
        } else {
            stgcmtscu.setUIDSuffix(cl.getOptionValue("uid-suffix"));
            storescu.setUIDSuffix(cl.getOptionValue("uid-suffix"));
            mppsscu.setUIDSuffix(cl.getOptionValue("uid-suffix"));
            scanFiles(cl.getArgList(), tmpPrefix, tmpSuffix, tmpDir, mppsscu, storescu, stgcmtscu);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        device.setExecutor(executorService);
        device.setScheduledExecutor(scheduledExecutorService);
        device.bindConnections();
        try {
            boolean sendMpps = cl.hasOption("mpps");
            boolean sendLateMpps = cl.hasOption("mpps-late");
            if (sendMpps || sendLateMpps)
                sendMpps(mppsscu, sendMpps);
            addReferencedPerformedProcedureStepSequence(mppsiuid, storescu);
            sendObjects(storescu);
            if (sendLateMpps)
                sendMppsNSet(mppsscu);
            if (cl.hasOption("stgcmt"))
                sendStgCmt(stgcmtscu);
        } finally {
            if (conn.isListening()) {
                device.waitForNoOpenConnections();
                device.unbindConnections();
            }
            executorService.shutdown();
            scheduledExecutorService.shutdown();
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.StoreSCU.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    long t1, t2;/* w w w  . j a  v  a 2s  .c om*/
    try {
        CommandLine cl = parseComandLine(args);
        Device device = new Device("storescu");
        Connection conn = new Connection();
        device.addConnection(conn);
        ApplicationEntity ae = new ApplicationEntity("STORESCU");
        device.addApplicationEntity(ae);
        ae.addConnection(conn);
        StoreSCU main = new StoreSCU(ae);
        configureTmpFile(main, cl);
        CLIUtils.configureConnect(main.remote, main.rq, cl);
        CLIUtils.configureBind(conn, ae, cl);
        CLIUtils.configure(conn, cl);
        main.remote.setTlsProtocols(conn.getTlsProtocols());
        main.remote.setTlsCipherSuites(conn.getTlsCipherSuites());
        configureRelatedSOPClass(main, cl);
        main.setAttributes(new Attributes());
        CLIUtils.addAttributes(main.attrs, cl.getOptionValues("s"));
        main.setUIDSuffix(cl.getOptionValue("uid-suffix"));
        main.setPriority(CLIUtils.priorityOf(cl));
        List<String> argList = cl.getArgList();
        boolean echo = argList.isEmpty();
        if (!echo) {
            System.out.println(rb.getString("scanning"));
            t1 = System.currentTimeMillis();
            main.scanFiles(argList);
            t2 = System.currentTimeMillis();
            int n = main.filesScanned;
            System.out.println();
            if (n == 0)
                return;
            System.out.println(
                    MessageFormat.format(rb.getString("scanned"), n, (t2 - t1) / 1000F, (t2 - t1) / n));
        }
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        device.setExecutor(executorService);
        device.setScheduledExecutor(scheduledExecutorService);
        try {
            t1 = System.currentTimeMillis();
            main.open();
            t2 = System.currentTimeMillis();
            System.out
                    .println(MessageFormat.format(rb.getString("connected"), main.as.getRemoteAET(), t2 - t1));
            if (echo)
                main.echo();
            else {
                t1 = System.currentTimeMillis();
                main.sendFiles();
                t2 = System.currentTimeMillis();
            }
        } finally {
            main.close();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
        }
        if (main.filesScanned > 0) {
            float s = (t2 - t1) / 1000F;
            float mb = main.totalSize / 1048576F;
            System.out.println(MessageFormat.format(rb.getString("sent"), main.filesSent, mb, s, mb / s));
        }
    } catch (ParseException e) {
        System.err.println("storescu: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("storescu: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.dcm4che3.tool.ihe.modality.Modality.java

@SuppressWarnings({ "unchecked" })
public static void main(String[] args) {
    try {//from  w w  w .ja va  2  s .c o m
        CommandLine cl = parseComandLine(args);
        if (cl.getArgList().isEmpty())
            throw new MissingOptionException(rb.getString("missing-i-file"));
        final Device device = new Device("modality");
        final Connection conn = new Connection();
        final ApplicationEntity ae = new ApplicationEntity("MODALITY");
        checkOptions(cl);
        CLIUtils.configureBind(conn, ae, cl);
        CLIUtils.configure(conn, cl);
        device.addConnection(conn);
        device.addApplicationEntity(ae);
        ae.addConnection(conn);
        final MppsSCU mppsscu = new MppsSCU(ae);
        final StoreSCU storescu = new StoreSCU(ae);
        final StgCmtSCU stgcmtscu = new StgCmtSCU(ae);
        CLIUtils.configureConnect(mppsscu.getRemoteConnection(), mppsscu.getAAssociateRQ(), cl);
        CLIUtils.configureConnect(stgcmtscu.getRemoteConnection(), stgcmtscu.getAAssociateRQ(), cl);
        CLIUtils.configureConnect(storescu.getRemoteConnection(), storescu.getAAssociateRQ(), cl);
        calledAET = storescu.getAAssociateRQ().getCalledAET();
        mppsscu.setTransferSyntaxes(CLIUtils.transferSyntaxesOf(cl));
        mppsscu.setCodes(
                CLIUtils.loadProperties(cl.getOptionValue("code-config", "resource:code.properties"), null));
        if (cl.hasOption("dc"))
            mppsscu.setFinalStatus("DISCONTINUED");
        if (cl.hasOption("dc-reason"))
            mppsscu.setDiscontinuationReason(cl.getOptionValue("dc-reason"));
        stgcmtscu.setTransferSyntaxes(CLIUtils.transferSyntaxesOf(cl));
        stgcmtscu.setStorageDirectory(StgCmtSCU.getStorageDirectory(cl));
        StoreSCU.configureRelatedSOPClass(storescu, cl);
        storescu.setUIDSuffix(StoreSCU.uidSuffixOf(cl));
        Attributes attrs = new Attributes();
        CLIUtils.addAttributes(attrs, cl.getOptionValues("s"));
        mppsscu.setAttributes(attrs);
        storescu.setAttributes(attrs);
        stgcmtscu.setAttributes(attrs);
        setTlsParams(mppsscu.getRemoteConnection(), conn);
        setTlsParams(storescu.getRemoteConnection(), conn);
        setTlsParams(stgcmtscu.getRemoteConnection(), conn);
        String tmpPrefix = "iocmtest-";
        String tmpSuffix = null;
        File tmpDir = null;
        configureTmpFile(storescu, tmpPrefix, tmpSuffix, tmpDir, cl);
        String mppsiuid = UIDUtils.createUID();
        mppsscu.setPPSUID(mppsiuid);
        if (cl.hasOption("kos-title")) {
            List<String> fname = Arrays.asList(mkkos(cl));
            scanFiles(fname, tmpPrefix, tmpSuffix, tmpDir, mppsscu, storescu, stgcmtscu);
        } else {
            stgcmtscu.setUIDSuffix(cl.getOptionValue("uid-suffix"));
            storescu.setUIDSuffix(cl.getOptionValue("uid-suffix"));
            mppsscu.setUIDSuffix(cl.getOptionValue("uid-suffix"));
            scanFiles(cl.getArgList(), tmpPrefix, tmpSuffix, tmpDir, mppsscu, storescu, stgcmtscu);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        device.setExecutor(executorService);
        device.setScheduledExecutor(scheduledExecutorService);
        device.bindConnections();
        try {
            boolean sendMpps = cl.hasOption("mpps");
            boolean sendLateMpps = cl.hasOption("mpps-late");
            if (sendMpps || sendLateMpps) {
                sendMpps(mppsscu, sendMpps);
                addReferencedPerformedProcedureStepSequence(mppsiuid, storescu);
            } else {
                nullifyReferencedPerformedProcedureStepSequence(storescu);
            }
            sendObjects(storescu);
            if (sendLateMpps)
                sendMppsNSet(mppsscu);
            if (cl.hasOption("stgcmt"))
                sendStgCmt(stgcmtscu);
        } finally {
            if (conn.isListening()) {
                device.waitForNoOpenConnections();
                device.unbindConnections();
            }
            executorService.shutdown();
            scheduledExecutorService.shutdown();
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:com.comcast.cqs.test.stress.CqsStressTester.java

/**
* @param args//  w ww . ja  v a  2 s  .  c o m
*/
public static void main(String[] args) {

    try {

        CMBControllerServlet.valueAccumulator.initializeAllCounters();
        setup();
        Util.initLog4j();
        CqsStressTester tester = new CqsStressTester();
        ScheduledExecutorService scheduledExecutorService = tester
                .createQueuesAndInitializePublishersAndReceivers(); //will clear queues

        long totalMessagesReceived = 0;
        long totalMessagesDeleted = 0;
        long totalMessagesRevisibled = 0;
        long totalEmptyResponses = 0;
        long totalDuplicates = 0;
        long totalOutOfOrderMessages = 0;

        int testDurationSeconds = CQSStressTestProperties.getInstance().getTestDurationSeconds();
        Thread.sleep(testDurationSeconds * 1000);

        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }

        logger.info("===Sender Shutdown Triggered==");

        for (String queueUrl : tester.receiverMap.keySet()) {
            for (Receiver receiver : tester.receiverMap.get(queueUrl)) {
                receiver.setContinueThread(false);
            }
        }

        for (String queueUrl : tester.receiverMap.keySet()) {

            Set<String> messageIdMaster = new HashSet<String>();
            List<Integer> deleteTimesMaster = new ArrayList<Integer>();
            List<Long> flightTimesMaster = new ArrayList<Long>();
            List<Long> receiveTimesMaster = new ArrayList<Long>();

            for (Receiver receiver : tester.receiverMap.get(queueUrl)) {

                receiver.join();

                logger.warn(
                        "===================================================================================================================");
                logger.warn("TheadId=" + receiver.getThreadId() + " receiveMessageCount="
                        + receiver.getTotalMessagesReceived() + " deletedMessageCount="
                        + receiver.getTotalMessagesDeleted() + " revisibledMessageCount="
                        + receiver.getTotalMessagesRevisibled());
                logger.warn(
                        "===================================================================================================================");

                totalMessagesReceived += receiver.getTotalMessagesReceived();
                totalMessagesDeleted += receiver.getTotalMessagesDeleted();
                totalMessagesRevisibled += receiver.getTotalMessagesRevisibled();
                totalOutOfOrderMessages += receiver.getTotalOutOfOrderMessages();
                totalDuplicates += checkAndCombine(messageIdMaster, receiver.messageIds);
                //deleteTimesMaster.addAll(receiver.deleteLatencyMSList);
                //flightTimesMaster.addAll(receiver.flightTimeList);
                totalEmptyResponses += receiver.emptyResponseCount;
            }

            logger.warn(
                    "===================================================================================================================");

            Iterator<String> iter = sendMessageIdSet.iterator();

            while (iter.hasNext()) {
                logger.error("Missed message:" + iter.next());
            }

            Collections.sort(deleteTimesMaster);
            Collections.sort(flightTimesMaster);
            //receiveTimesMaster.addAll(receiveLacencyMSList);
            Collections.sort(receiveTimesMaster);

            /*logger.warn("Receive message latencies");
                    
            if (receiveTimesMaster.size() > 0) {
                    
               for (int i=5; i<=100; i+=5) {
                    
                  int percentileIndex = receiveTimesMaster.size()*i/100 - 1;
                    
                  if (percentileIndex < 0) {
             percentileIndex = 0;
                  }
                    
                  logger.warn("" + i + "th percentile=" + receiveTimesMaster.get(percentileIndex));
               }
            }
                    
            logger.warn("===================================================================================================================");
            logger.warn("Message flight time latencies");
                    
            if (flightTimesMaster.size() > 0) {
                    
               for (int i=5; i<=100; i+=5) {
                    
                  int percentileIndex = flightTimesMaster.size()*i/100 - 1;
                    
                  if (percentileIndex < 0) {
             percentileIndex = 0;
                  }
                    
                  logger.warn("" + i + "th percentile=" + flightTimesMaster.get(percentileIndex));
               }
            }
                    
            logger.warn("===================================================================================================================");
            logger.warn("Delete message latencies");
                    
            if (deleteTimesMaster.size() > 0) {
                    
               for (int i=5; i<=100; i+=5) {
                    
                  int percentileIndex = deleteTimesMaster.size()*i/100 - 1;
                    
                  if (percentileIndex < 0) {
             percentileIndex = 0;
                  }
                    
                  logger.warn("" + i + "th percentile=" + deleteTimesMaster.get(percentileIndex));
               }
            }*/

        }

        logger.warn(
                "===================================================================================================================");
        logger.warn(
                "===================================================================================================================");
        logger.warn("totalMessagesSent=" + tester.messageCount.get() + " totalMessagesReceived="
                + totalMessagesReceived + " totalMessagesDeleted=" + totalMessagesDeleted
                + " totalMessagesRevisibled=" + totalMessagesRevisibled);
        logger.warn(
                "===================================================================================================================");
        logger.warn("totalEmptyResponses=" + totalEmptyResponses);
        logger.warn("totalDuplicates=" + totalDuplicates);
        logger.warn("totalOutOfOrderMessages=" + totalOutOfOrderMessages);
        logger.warn("totalMessagesLost=" + sendMessageIdSet.size());
        logger.warn(
                "===================================================================================================================");
        logger.warn("totalRunTimeMillis=" + (System.currentTimeMillis() - tester.startTime) + " status=Exit");
        logger.warn(
                "===================================================================================================================");
        logger.warn(
                "===================================================================================================================");

    } catch (Exception e) {
        logger.error("Thread=main status=exception message=setup_failure ", e);
    } finally {
        CMBControllerServlet.valueAccumulator.deleteAllCounters();
    }
}

From source file:org.janusgraph.TestBed.java

/**
 * @param args/*w w w.jav  a  2s.c om*/
 * @throws java.io.IOException
 */
public static void main(String[] args) throws Exception {
    Method method = TestBed.class.getMethod("getInt", int.class, int.class);
    AnnotatedType rt = method.getAnnotatedReturnType();
    System.out.println(rt.getType());
    System.out.println(rt.getAnnotations().length);
    System.out.println(method.getAnnotations().length);
    for (int i = 0; i < method.getAnnotations().length; i++) {
        System.out.println(method.getAnnotations()[i]);
    }

    //        String[] s = {"a","b","c","d","e","f","g","h","i","x","u"};
    //        int len = s.length;
    //        Random random = new Random();
    //
    //        Context c = new Context(new ObserverManager(),Observer.NO_OP);
    //        //Warmup
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long before = System.nanoTime();
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long total = System.nanoTime()-before;
    //        System.out.println("Total time: " + total/1000000);

    System.exit(0);

    final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1, new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            r.run();
        }
    });
    ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() {
        AtomicInteger atomicInt = new AtomicInteger(0);

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    exe.submit(new Runnable() {

                        private final int number = atomicInt.incrementAndGet();

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(150);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(number);
                        }
                    });
                    System.out.println("Submitted: " + i);
                    //                    doSomethingExpensive(20);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 0, 1, TimeUnit.SECONDS);
    Thread.sleep(10000);
    //        future.get(1,TimeUnit.SECONDS);
    System.out.println("Cancel: " + future.cancel(false));
    System.out.println("Done: " + future.isDone());
    exe.shutdown();
    //        Thread.sleep(2000);
    System.out.println("Terminate: " + exe.awaitTermination(5, TimeUnit.SECONDS));
    System.out.println("DONE");
    NonBlockingHashMapLong<String> id1 = new NonBlockingHashMapLong<String>(128);
    ConcurrentHashMap<Long, String> id2 = new ConcurrentHashMap<Long, String>(128, 0.75f, 2);

}

From source file:eu.itesla_project.online.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {/*from   w  w  w  .j a  v  a  2s .  com*/
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        String mode = line.getOptionValue("m");
        Path tmpDir = Paths.get(line.getOptionValue("t"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("f"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("s"));
        String statisticsDbName = line.getOptionValue("d");
        int coresPerRank = Integer.parseInt(line.getOptionValue("n"));
        Path stdOutArchive = line.hasOption("o") ? Paths.get(line.getOptionValue("o")) : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService executorService = MultiStateNetworkAwareExecutors.newCachedThreadPool();
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName);
            try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                    mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                OnlineConfig config = OnlineConfig.load();
                try (LocalOnlineApplication application = new LocalOnlineApplication(config, computationManager,
                        scheduledExecutorService, executorService, true)) {
                    switch (mode) {
                    case "ui":
                        System.out.println("LocalOnlineApplication created");
                        System.out.println("Waiting till shutdown");
                        // indefinitely wait for JMX commands
                        //TimeUnit.DAYS.sleep(Integer.MAX_VALUE);
                        synchronized (application) {
                            try {
                                application.wait();
                            } catch (InterruptedException ex) {
                            }

                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Invalid mode " + mode);
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
            executorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:eu.itesla_project.offline.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {/*from   w w w. j  a v a 2s  . c  om*/
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        Mode mode = Mode.valueOf(line.getOptionValue("mode"));
        String simulationDbName = line.hasOption("simulation-db-name")
                ? line.getOptionValue("simulation-db-name")
                : OfflineConfig.DEFAULT_SIMULATION_DB_NAME;
        String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name")
                : OfflineConfig.DEFAULT_RULES_DB_NAME;
        String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name")
                : OfflineConfig.DEFAULT_METRICS_DB_NAME;
        Path tmpDir = Paths.get(line.getOptionValue("tmp-dir"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir"));
        String statisticsDbName = line.getOptionValue("statistics-db-name");
        int coresPerRank = Integer.parseInt(line.getOptionValue("cores"));
        Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive"))
                : null;
        String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors
                .newSizeLimitedThreadPool("OFFLINE_POOL", 100);
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) {
                try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                        mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                    OfflineConfig config = OfflineConfig.load();
                    try (LocalOfflineApplication application = new LocalOfflineApplication(config,
                            computationManager, simulationDbName, rulesDbName, metricsDbName,
                            scheduledExecutorService, offlineExecutorService)) {
                        switch (mode) {
                        case ui:
                            application.await();
                            break;

                        case simulations: {
                            if (workflowId == null) {
                                workflowId = application.createWorkflow(null,
                                        OfflineWorkflowCreationParameters.load());
                            }
                            application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load());
                        }
                            break;

                        case rules: {
                            if (workflowId == null) {
                                throw new RuntimeException("Workflow '" + workflowId + "' not found");
                            }
                            application.computeSecurityRulesAndWait(workflowId);
                        }
                            break;

                        default:
                            throw new IllegalArgumentException("Invalid mode " + mode);
                        }
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            offlineExecutorService.shutdown();
            scheduledExecutorService.shutdown();
            offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:edu.umass.cs.nio.MessageNIOTransport.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    int msgNum = 0;
    int port = 2000;
    int nNodes = 100;
    SampleNodeConfig<Integer> snc = new SampleNodeConfig<Integer>(port);
    snc.localSetup(nNodes + 2);/*  w  w  w . j av a  2 s.  c  om*/
    MessageExtractor[] workers = new MessageExtractor[nNodes + 1];
    for (int i = 0; i < nNodes + 1; i++) {
        workers[i] = new MessageExtractor(new PacketDemultiplexerDefault());
    }
    MessageNIOTransport<?, ?>[] niots = new MessageNIOTransport[nNodes];

    try {
        int smallNNodes = 2;
        for (int i = 0; i < smallNNodes; i++) {
            niots[i] = new MessageNIOTransport<Integer, JSONObject>(i, snc, workers[i]);
            new Thread(niots[i]).start();
        }

        /* Test a few simple hellos. The sleep is there to test that the
         * successive writes do not "accidentally" benefit from concurrency,
         * i.e., to check that OP_WRITE flags will be set correctly. */
        ((MessageNIOTransport<Integer, JSONObject>) niots[1]).sendToIDInternal(0,
                JSONify(msgNum++, "Hello from 1 to 0"));
        ((MessageNIOTransport<Integer, JSONObject>) niots[0]).sendToIDInternal(1,
                JSONify(msgNum++, "Hello back from 0 to 1"));
        ((MessageNIOTransport<Integer, JSONObject>) niots[0]).sendToIDInternal(1,
                JSONify(msgNum++, "Second hello back from 0 to 1"));
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ((MessageNIOTransport<Integer, JSONObject>) niots[0]).sendToIDInternal(1,
                JSONify(msgNum++, "Third hello back from 0 to 1"));
        ((MessageNIOTransport<Integer, JSONObject>) niots[1]).sendToIDInternal(0,
                JSONify(msgNum++, "Thank you for all the hellos back from 1 to 0"));
        // //////////////////////////////////////////////////////////////////////
        int seqTestNum = 1;
        Thread.sleep(2000);
        System.out.println("\n\n\nBeginning test of " + seqTestNum + " random, sequential messages");
        Thread.sleep(1000);

        // //////////////////////////////////////////////////////////////////////

        // Create the remaining nodes up to nNodes
        for (int i = smallNNodes; i < nNodes; i++) {
            niots[i] = new MessageNIOTransport<Integer, JSONObject>(i, snc, workers[i]);
            new Thread(niots[i]).start();
        }

        // Test a random, sequential communication pattern
        for (int i = 0; i < nNodes * seqTestNum; i++) {
            int k = (int) (Math.random() * nNodes);
            int j = (int) (Math.random() * nNodes);
            System.out.println("Message " + i + " with msgNum " + msgNum);
            ((MessageNIOTransport<Integer, JSONObject>) niots[k]).sendToIDInternal(j,
                    JSONify(msgNum++, "Hello from " + k + " to " + j));
        }

        int oneToOneTestNum = 1;
        // //////////////////////////////////////////////////////////////////////

        Thread.sleep(1000);
        System.out.println("\n\n\nBeginning test of " + oneToOneTestNum * nNodes
                + " random, concurrent, 1-to-1 messages with emulated delays");
        Thread.sleep(1000);
        // //////////////////////////////////////////////////////////////////////

        // Random, concurrent communication pattern with emulated delays
        ScheduledExecutorService execpool = Executors.newScheduledThreadPool(5);
        class TX extends TimerTask {

            MessageNIOTransport<Integer, JSONObject> sndr = null;
            private int rcvr = -1;
            int msgNum = -1;

            TX(int i, int id, MessageNIOTransport<?, ?>[] n, int m) {
                sndr = (MessageNIOTransport<Integer, JSONObject>) n[i];
                rcvr = id;
                msgNum = m;
            }

            TX(MessageNIOTransport<Integer, JSONObject> niot, int id, int m) {
                sndr = niot;
                rcvr = id;
                msgNum = m;
            }

            public void run() {
                try {
                    sndr.sendToIDInternal(rcvr, JSONify(msgNum, "Hello from " + sndr.myID + " to " + rcvr));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        JSONDelayEmulator.emulateDelays();

        MessageNIOTransport<Integer, JSONObject> concurrentSender = new MessageNIOTransport<Integer, JSONObject>(
                nNodes, snc, workers[nNodes]);
        new Thread(concurrentSender).start();
        ScheduledFuture<?>[] futuresRandom = new ScheduledFuture[nNodes * oneToOneTestNum];
        for (int i = 0; i < nNodes * oneToOneTestNum; i++) {
            TX task = new TX(concurrentSender, 0, msgNum++);
            System.out.println("Scheduling random message " + i + " with msgNum " + msgNum);
            futuresRandom[i] = execpool.schedule(task, 0, TimeUnit.MILLISECONDS);
        }
        for (int i = 0; i < nNodes * oneToOneTestNum; i++) {
            try {
                futuresRandom[i].get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // //////////////////////////////////////////////////////////////////////
        Thread.sleep(1000);
        System.out.println(
                "\n\n\nBeginning test of random, concurrent, " + " any-to-any messages with emulated delays");
        Thread.sleep(1000);
        // //////////////////////////////////////////////////////////////////////

        int load = nNodes * 25;
        int msgsToFailed = 0;
        ScheduledFuture<?>[] futures = new ScheduledFuture[load];
        for (int i = 0; i < load; i++) {
            int k = (int) (Math.random() * nNodes);
            int j = (int) (Math.random() * nNodes);
            // long millis = (long)(Math.random()*1000);

            if (i % 100 == 0) {
                // Periodically try sending to a non-existent node
                j = nNodes + 1;
                msgsToFailed++;
            }

            TX task = new TX(k, j, niots, msgNum++);
            System.out.println("Scheduling random message " + i + " with msgNum " + msgNum);
            futures[i] = (ScheduledFuture<?>) execpool.schedule(task, 0, TimeUnit.MILLISECONDS);
        }
        int numExceptions = 0;
        for (int i = 0; i < load; i++) {
            try {
                futures[i].get();
            } catch (Exception e) {
                // e.printStackTrace();
                numExceptions++;
            }
        }

        // ////////////////////////////////////////////////////////////////
        Thread.sleep(2000);
        System.out.println("\n\n\nPrinting overall stats. Number of exceptions =  " + numExceptions);
        System.out.println((new NIOInstrumenter() + "\n"));
        boolean pending = false;
        for (int i = 0; i < nNodes; i++) {
            if (niots[i].getPendingSize() > 0) {
                System.out.println("Pending messages at node " + i + " : " + niots[i].getPendingSize());
                pending = true;
            }
        }
        int missing = NIOInstrumenter.getMissing();
        assert (pending == false || missing == msgsToFailed) : "Unsent pending messages in NIO";
        for (NIOTransport<?> niot : niots) {
            niot.stop();
        }
        concurrentSender.stop();
        execpool.shutdown();

        if (!pending || missing == msgsToFailed) {
            System.out.println("\nSUCCESS: no pending messages to non-failed nodes!");
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}