Example usage for java.util.concurrent Executors newScheduledThreadPool

List of usage examples for java.util.concurrent Executors newScheduledThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newScheduledThreadPool.

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

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

public static void main(String[] args) throws Exception {
    try {/* w ww. jav a2s  .  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:org.graylog2.Main.java

/**
 * @param args the command line arguments
 *//*from  www. j  av  a2  s.  c  o m*/
public static void main(String[] args) {

    CommandLineArguments commandLineArguments = new CommandLineArguments();
    JCommander jCommander = new JCommander(commandLineArguments, args);
    jCommander.setProgramName("graylog2");

    if (commandLineArguments.isShowHelp()) {
        jCommander.usage();
        System.exit(0);
    }

    if (commandLineArguments.isShowVersion()) {
        System.out.println("Graylog2 Server " + GRAYLOG2_VERSION);
        System.out.println("JRE: " + Tools.getSystemInformation());
        System.exit(0);
    }

    // Are we in debug mode?
    if (commandLineArguments.isDebug()) {
        LOG.info("Running in Debug mode");
        Logger.getRootLogger().setLevel(Level.ALL);
        Logger.getLogger(Main.class.getPackage().getName()).setLevel(Level.ALL);
    }

    LOG.info("Graylog2 starting up. (JRE: " + Tools.getSystemInformation() + ")");

    String configFile = commandLineArguments.getConfigFile();
    LOG.info("Using config file: " + configFile);

    configuration = new Configuration();
    JadConfig jadConfig = new JadConfig(new PropertiesRepository(configFile), configuration);

    LOG.info("Loading configuration");
    try {
        jadConfig.process();
    } catch (RepositoryException e) {
        LOG.fatal("Couldn't load configuration file " + configFile, e);
        System.exit(1);
    } catch (ValidationException e) {
        LOG.fatal("Invalid configuration", e);
        System.exit(1);
    }

    // If we only want to check our configuration, we can gracefully exit here
    if (commandLineArguments.isConfigTest()) {
        System.exit(0);
    }

    /*
     * Check if the index exists. Create it if not.
     * (Try this a few times to allow ElasticSearch to come up.)
     */
    boolean indexNotChecked = true;
    int indexCheckIntervalCount = 1;
    while (indexNotChecked) {
        try {
            if (checkAndCreateIndex()) {
                break;
            }
        } catch (IOException e) {
            LOG.warn("Could not check for or create ElasticSearch index. [" + indexCheckIntervalCount + "] "
                    + "Retrying in " + INDEX_CHECK_INTERVAL_SEC + " seconds.", e);
        }

        // Abort if last retry failed.
        if (indexCheckIntervalCount == INDEX_CHECK_RETRIES) {
            LOG.fatal("Could not check for ElasticSearch index after " + INDEX_CHECK_RETRIES + " retries."
                    + "Make sure that your ElasticSearch server is running.");
            System.exit(1);
        }

        indexCheckIntervalCount++;
        try {
            Thread.sleep(INDEX_CHECK_INTERVAL_SEC * 1000);
        } catch (InterruptedException e) {
        }
    }

    savePidFile(commandLineArguments.getPidFile());

    // Statically set timeout for LogglyForwarder.
    // TODO: This is a code smell and needs to be fixed.
    LogglyForwarder.setTimeout(configuration.getForwarderLogglyTimeout());

    scheduler = Executors.newScheduledThreadPool(SCHEDULED_THREADS_POOL_SIZE);

    initializeMongoConnection(configuration);
    initializeRulesEngine(configuration.getDroolsRulesFile());
    initializeSyslogServer(configuration.getSyslogProtocol(), configuration.getSyslogListenPort());
    initializeHostCounterCache(scheduler);

    // Start message counter thread.
    initializeMessageCounters(scheduler);

    // Inizialize message queue.
    initializeMessageQueue(scheduler, configuration);

    // Write initial ServerValue information.
    writeInitialServerValues(configuration);

    // Start GELF threads
    if (configuration.isUseGELF()) {
        initializeGELFThreads(configuration.getGelfListenAddress(), configuration.getGelfListenPort(),
                scheduler);
    }

    // Initialize AMQP Broker if enabled
    if (configuration.isAmqpEnabled()) {
        initializeAMQP(configuration);
    }

    // Start server value writer thread. (writes for example msg throughout and pings)
    initializeServerValueWriter(scheduler);

    // Start thread that automatically removes messages older than retention time.
    if (commandLineArguments.performRetention()) {
        initializeMessageRetentionThread(scheduler);
    } else {
        LOG.info("Not initializing retention time cleanup thread because --no-retention was passed.");
    }

    // Add a shutdown hook that tries to flush the message queue.
    Runtime.getRuntime().addShutdownHook(new MessageQueueFlusher());

    LOG.info("Graylog2 up and running.");
}

From source file:Main.java

public static ExecutorService getScheduledThreadPool(int corePoolSize) {
    return Executors.newScheduledThreadPool(corePoolSize);
}

From source file:Main.java

public static void newScheduledThreadPoolAtFixedRate(Runnable runnable, long delayTime, long period, int size) {
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(size);
    scheduledThreadPool.scheduleAtFixedRate(runnable, delayTime, period, TimeUnit.SECONDS);
}

From source file:Main.java

public static ScheduledExecutorService getScheduler() {

    if (POOL.isShutdown() || POOL.isTerminated()) {

        POOL = Executors.newScheduledThreadPool(10);

    }//  ww w  . j a  v a  2 s  .c  o m

    THREADS++;
    //Log.d("ThreadHelper", "thread count :" + THREADS);

    return POOL;

}

From source file:Main.java

/***
 * // w  ww. ja  va 2 s.c om
 * @param runnable
 * @param delayTime
 * @param size
 */
public static void newScheduedThreadPool(Runnable runnable, long delayTime, int size) {
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(size);
    scheduledThreadPool.schedule(runnable, delayTime, TimeUnit.SECONDS);
}

From source file:com.tellapart.taba.TabaApiFactory.java

public static synchronized void initialize(TabaClientProperties properties) {
    Preconditions.checkState(engine == null, "Already initialized.");

    TabaClientEngine clientEngine = new DefaultClientEngine(properties, HttpClients.createDefault(),
            Executors.newScheduledThreadPool(1));

    initialize(clientEngine);/*from  w w w. j  a va  2s  .c  o m*/
}

From source file:interactivespaces.system.ActiveTestInteractiveSpacesEnvironment.java

/**
 * Create a new {@link ActiveTestInteractiveSpacesEnvironment}.
 *
 * @return the space environment/*  ww  w.j a  v  a  2  s  .  c om*/
 */
public static ActiveTestInteractiveSpacesEnvironment newActiveTestInteractiveSpacesEnvironment() {
    ActiveTestInteractiveSpacesEnvironment environment = new ActiveTestInteractiveSpacesEnvironment();

    environment.systemConfiguration = SimpleConfiguration.newConfiguration();
    environment.executorService = Executors.newScheduledThreadPool(100);
    environment.log = new Jdk14Logger("test.interactive.spaces");
    environment.serviceRegistry = new SimpleServiceRegistry(environment);
    environment.timeProvider = new SettableTimeProvider();

    return environment;
}

From source file:interactivespaces.system.StandaloneInteractiveSpacesEnvironment.java

/**
 * Create a new {@link StandaloneInteractiveSpacesEnvironment}.
 *
 * @return the space environment/*ww  w .j a  va 2 s.  c o  m*/
 */
public static StandaloneInteractiveSpacesEnvironment newStandaloneInteractiveSpacesEnvironment() {
    StandaloneInteractiveSpacesEnvironment environment = new StandaloneInteractiveSpacesEnvironment();

    environment.systemConfiguration = SimpleConfiguration.newConfiguration();
    environment.executorService = Executors.newScheduledThreadPool(100);
    environment.log = new Jdk14Logger("test.interactive.spaces");
    environment.serviceRegistry = new SimpleServiceRegistry(environment);
    environment.timeProvider = new SettableTimeProvider();
    environment.managedResources = new ManagedResources(environment.log);
    environment.managedResources.startupResources();

    return environment;
}

From source file:ru.jts_dev.gameserver.config.ThreadPoolConfig.java

@Bean
public ScheduledExecutorService scheduledExecutorService() {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);
    return scheduler;
}