Example usage for java.util.concurrent ScheduledExecutorService awaitTermination

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

Introduction

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

Prototype

boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Usage

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

/**
 * Sends messages to registered devices/* w w w .j ava  2s  .  co  m*/
 */
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.janusgraph.TestBed.java

/**
 * @param args/*from   w  w  w  .  ja v a 2 s.c  o  m*/
 * @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 {//w  w w . j a  v a2  s. c o m
        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  a2 s  .  c  o m
        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:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java

/**
 * Runs a number of threads which generate metrics.
 *///from  w  w w. j a  v a  2s.  com
public static void generateMetrics(final MetricRegistry metrics, final long metricsToGenerate, final int period,
        final TimeUnit periodTimeUnit, HadoopMetrics2Reporter metrics2Reporter, int numThreads)
        throws Exception {
    final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads);
    final CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        final int id = i;
        final int halfPeriod = (period / 2);
        Runnable task = new Runnable() {
            private long executions = 0;
            final Random r = new Random();

            @Override
            public void run() {
                if (executions >= metricsToGenerate) {
                    return;
                }
                metrics.counter("foo counter thread" + id).inc();
                executions++;
                if (executions < metricsToGenerate) {
                    pool.schedule(this, period + r.nextInt(halfPeriod), periodTimeUnit);
                } else {
                    latch.countDown();
                }
            }
        };
        pool.schedule(task, period, periodTimeUnit);
    }

    while (!latch.await(2, TimeUnit.SECONDS)) {
        metrics2Reporter.printQueueDebugMessage();
    }

    pool.shutdown();
    pool.awaitTermination(5000, TimeUnit.SECONDS);
}

From source file:net.sourceforge.fullsync.cli.Main.java

public static void startup(String[] args, Launcher launcher) throws Exception {
    initOptions();/*  w  w w . j a v a2s .  c o m*/
    String configDir = getConfigDir();
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;

    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        printHelp();
        System.exit(1);
    }

    if (line.hasOption('V')) {
        System.out.println(String.format("FullSync version %s", Util.getFullSyncVersion())); //$NON-NLS-1$
        System.exit(0);
    }

    // Apply modifying options
    if (!line.hasOption("v")) { //$NON-NLS-1$
        System.setErr(new PrintStream(new FileOutputStream(getLogFileName())));
    }

    if (line.hasOption("h")) { //$NON-NLS-1$
        printHelp();
        System.exit(0);
    }

    upgradeLegacyPreferencesLocation(configDir);

    String profilesFile;
    if (line.hasOption("P")) { //$NON-NLS-1$
        profilesFile = line.getOptionValue("P"); //$NON-NLS-1$
    } else {
        profilesFile = configDir + FullSync.PROFILES_XML;
        upgradeLegacyProfilesXmlLocation(profilesFile);
    }
    final String prefrencesFile = configDir + FullSync.PREFERENCES_PROPERTIES;
    final Injector injector = Guice.createInjector(new FullSyncModule(line, prefrencesFile));
    final RuntimeConfiguration rtConfig = injector.getInstance(RuntimeConfiguration.class);
    injector.getInstance(ProfileManager.class).setProfilesFileName(profilesFile);
    final ScheduledExecutorService scheduledExecutorService = injector
            .getInstance(ScheduledExecutorService.class);
    final EventListener deadEventListener = new EventListener() {
        private final Logger logger = LoggerFactory.getLogger("DeadEventLogger"); //$NON-NLS-1$

        @Subscribe
        private void onDeadEvent(DeadEvent deadEvent) {
            if (!(deadEvent.getEvent() instanceof ShutdownEvent)) {
                logger.warn("Dead event triggered: {}", deadEvent); //$NON-NLS-1$
            }
        }
    };
    final EventBus eventBus = injector.getInstance(EventBus.class);
    eventBus.register(deadEventListener);

    final Semaphore sem = new Semaphore(0);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        Logger logger = LoggerFactory.getLogger(Main.class);
        logger.debug("shutdown hook called, starting orderly shutdown"); //$NON-NLS-1$
        eventBus.post(new ShutdownEvent());
        scheduledExecutorService.shutdown();
        try {
            scheduledExecutorService.awaitTermination(5, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // not relevant
        }
        logger.debug("shutdown hook finished, releaseing main thread semaphore"); //$NON-NLS-1$
        sem.release();
    }));
    if (rtConfig.isDaemon().orElse(false).booleanValue() || rtConfig.getProfileToRun().isPresent()) {
        finishStartup(injector);
        sem.acquireUninterruptibly();
        System.exit(0);
    } else {
        launcher.launchGui(injector);
        System.exit(0);
    }
}

From source file:com.ah.be.license.AeroLicenseTimer.java

/**
 * Stop your defined license timer./*  w w w.j ava2 s  .  c  o m*/
 *
 * @param arg_Timer -
 * @param arg_Future -
 * @return String : the error message
 */
public static String stopLicenseTimer(ScheduledExecutorService arg_Timer, ScheduledFuture<?> arg_Future) {
    try {
        if (!arg_Timer.isShutdown()) {

            if (null != arg_Future) {
                arg_Future.cancel(false);
            }

            // Disable new tasks from being submitted.
            arg_Timer.shutdown();
            try {
                // Wait a while for existing tasks to terminate.
                if (!arg_Timer.awaitTermination(5, TimeUnit.SECONDS)) {
                    // Cancel currently executing tasks.
                    arg_Timer.shutdownNow();

                    // Wait a while for tasks to respond to being canceled.
                    if (!arg_Timer.awaitTermination(5, TimeUnit.SECONDS)) {
                        return "The license timer does not terminate.";
                    }
                }
            } catch (InterruptedException ie) {
                // (Re-)Cancel if current thread also interrupted.
                //arg_Timer.shutdownNow();
            }
        }
    } catch (Exception e) {
        return "There is something wrong with timer stop.";
    }
    return null;
}

From source file:org.apache.flink.runtime.filecache.FileCache.java

/**
 * Shuts down the file cache by cancelling all
 *//*from ww  w.  ja  va  2s . c om*/
public void shutdown() {
    synchronized (lock) {
        // first shutdown the thread pool
        ScheduledExecutorService es = this.executorService;
        if (es != null) {
            es.shutdown();
            try {
                es.awaitTermination(5000L, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                // may happen
            }
        }

        entries.clear();

        // clean up the all storage directories
        for (File dir : storageDirectories) {
            try {
                FileUtils.deleteDirectory(dir);
            } catch (IOException e) {
                LOG.error("File cache could not properly clean up storage directory.");
            }
        }

        // Remove shutdown hook to prevent resource leaks, unless this is invoked by the
        // shutdown hook itself
        if (shutdownHook != null && shutdownHook != Thread.currentThread()) {
            try {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            } catch (IllegalStateException e) {
                // race, JVM is in shutdown already, we can safely ignore this
            } catch (Throwable t) {
                LOG.warn("Exception while unregistering file cache's cleanup shutdown hook.");
            }
        }
    }
}

From source file:com.all.download.manager.ScheduledExecutorServiceSingleton.java

public void destroy() {
    Iterator<ScheduledExecutorService> iterator = scheduledExecutorServiceList.iterator();

    while (iterator.hasNext()) {
        ScheduledExecutorService scheduledExecutorService = iterator.next();

        try {/*from  w  ww. ja  v  a2 s.  c  o  m*/
            // close the thread pool, should only be closed here but no harm if
            // it was closed somewhere else
            scheduledExecutorService.shutdown();
            if (!scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS)) {
                log.warn("Thread pool did not terminate correctly");
            }
        } catch (InterruptedException ie) {
            scheduledExecutorService.shutdownNow();
        }

        iterator.remove();
    }

}

From source file:com.pepaproch.gtswsdl.client.RateLimitTest.java

@Test
public void testCOnsumeSLotAsync() {
    RateLimit rate = new RateLimit(5, 10, ChronoUnit.SECONDS);
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
    final AtomicInteger cc = new AtomicInteger(0);
    Instant start = Instant.now();
    final Instant[] end = new Instant[1];

    Runnable r = () -> {/* w w w  .j  a  v a  2 s .com*/
        for (int i = 0; i < 21; i++) {
            addTask(cc, scheduler, rate, end);
        }
    };
    Runnable r1 = () -> {
        for (int i = 0; i < 9; i++) {
            addTask(cc, scheduler, rate, end);

        }
    };

    r1.run();
    r.run();

    try {

        scheduler.awaitTermination(5, TimeUnit.SECONDS);

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(Duration.between(start, end[0]).toMillis());
}