Example usage for java.util.concurrent ScheduledThreadPoolExecutor shutdown

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

Introduction

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

Prototype

public 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.fusesource.forge.jmstest.executor.BenchmarkController.java

@Override
synchronized public void stop() {

    coordinator.release();/*from  w  w  w.java 2s . com*/
    super.stop();

    log().info("BenchmarkController going down in 5 Seconds");

    final CountDownLatch brokerStopLatch = new CountDownLatch(1);
    final ScheduledThreadPoolExecutor waiter = new ScheduledThreadPoolExecutor(1);
    waiter.schedule(new Runnable() {
        public void run() {
            brokerStopLatch.countDown();
            waiter.shutdown();
        }
    }, 5, TimeUnit.SECONDS);

    try {
        brokerStopLatch.await();
    } catch (InterruptedException e1) {
    }

    if (broker != null) {
        log().info("Stopping embedded broker for Benchmark framework: ");
        try {
            broker.stop();
        } catch (Exception e) {
            // log().error("Embedded broker could not be stopped.", e);
        }
    }
}

From source file:com.btoddb.chronicle.plunkers.HdfsPlunkerImplTest.java

@Test
public void testShutdown(@Injectable final ScheduledThreadPoolExecutor closeExec, // don't want other executors affected
        @Injectable final ScheduledThreadPoolExecutor idleExec // don't want other executors affected
) throws Exception {
    new Expectations() {
        {/*from   www  . j a v a2s  . c o m*/
            idleExec.scheduleWithFixedDelay((Runnable) any, 10000, 10000, TimeUnit.MILLISECONDS);
            times = 1;
            idleExec.shutdown();
            times = 1;
            closeExec.shutdown();
            times = 1;
            closeExec.awaitTermination(plunker.getShutdownWaitTimeout(), TimeUnit.SECONDS);
            times = 1;
            result = true;
        }
    };
    plunker.setCloseExec(closeExec);
    plunker.setIdleTimerExec(idleExec);
    plunker.init(config);
    plunker.shutdown();
}

From source file:edu.berkeley.sparrow.examples.SimpleFrontend.java

public void run(String[] args) {
    try {/*  w w  w .j  ava  2 s .c o  m*/
        OptionParser parser = new OptionParser();
        parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
        parser.accepts("help", "print help statement");
        OptionSet options = parser.parse(args);

        if (options.has("help")) {
            parser.printHelpOn(System.out);
            System.exit(-1);
        }

        // Logger configuration: log to the console
        BasicConfigurator.configure();
        LOG.setLevel(Level.DEBUG);

        Configuration conf = new PropertiesConfiguration();

        if (options.has("c")) {
            String configFile = (String) options.valueOf("c");
            conf = new PropertiesConfiguration(configFile);
        }

        int arrivalPeriodMillis = conf.getInt(JOB_ARRIVAL_PERIOD_MILLIS, DEFAULT_JOB_ARRIVAL_PERIOD_MILLIS);
        int experimentDurationS = conf.getInt(EXPERIMENT_S, DEFAULT_EXPERIMENT_S);
        LOG.debug("Using arrival period of " + arrivalPeriodMillis + " milliseconds and running experiment for "
                + experimentDurationS + " seconds.");
        int tasksPerJob = conf.getInt(TASKS_PER_JOB, DEFAULT_TASKS_PER_JOB);
        int taskDurationMillis = conf.getInt(TASK_DURATION_MILLIS, DEFAULT_TASK_DURATION_MILLIS);

        int schedulerPort = conf.getInt(SCHEDULER_PORT, SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT);
        String schedulerHost = conf.getString(SCHEDULER_HOST, DEFAULT_SCHEDULER_HOST);
        client = new SparrowFrontendClient();
        client.initialize(new InetSocketAddress(schedulerHost, schedulerPort), APPLICATION_ID, this);

        JobLaunchRunnable runnable = new JobLaunchRunnable(tasksPerJob, taskDurationMillis);
        ScheduledThreadPoolExecutor taskLauncher = new ScheduledThreadPoolExecutor(1);
        taskLauncher.scheduleAtFixedRate(runnable, 0, arrivalPeriodMillis, TimeUnit.MILLISECONDS);

        long startTime = System.currentTimeMillis();
        LOG.debug("sleeping");
        while (System.currentTimeMillis() < startTime + experimentDurationS * 1000) {
            Thread.sleep(100);
        }
        taskLauncher.shutdown();
    } catch (Exception e) {
        LOG.error("Fatal exception", e);
    }
}

From source file:net.roboconf.iaas.openstack.IaasOpenstack.java

@Override
public String createVM(String machineImageId, String ipMessagingServer, String channelName,
        String applicationName) throws IaasException, CommunicationToIaasException {

    if (machineImageId == null || "".equals(machineImageId))
        machineImageId = this.machineImageId;

    // Normally we use flavor names in the configuration, not IDs
    // But lets's assume it can be an ID...
    String flavorId = this.flavor;
    Flavors flavors = this.novaClient.flavors().list(true).execute();
    for (Flavor f : flavors) {
        if (f.getName().equals(this.flavor))
            flavorId = f.getId();//from  w  ww  .j  a va2 s. co  m
    }

    ServerForCreate serverForCreate = new ServerForCreate();
    serverForCreate.setName(applicationName + "." + channelName);
    serverForCreate.setFlavorRef(flavorId);
    serverForCreate.setImageRef(machineImageId);
    if (this.keypair != null)
        serverForCreate.setKeyName(this.keypair);
    serverForCreate.getSecurityGroups().add(new ServerForCreate.SecurityGroup(this.securityGroup));

    // User data will be retrieved (like on Amazon WS) on guest OS as
    // http://169.254.169.254/latest/user-data
    String userData = "applicationName=" + applicationName + "\nmachineName=" + channelName //TBD machineName=channelName
            + "\nchannelName=" + channelName + "\nipMessagingServer=" + ipMessagingServer;
    serverForCreate.setUserData(new String(Base64.encodeBase64(userData.getBytes())));

    final Server server = this.novaClient.servers().boot(serverForCreate).execute();
    System.out.println(server);

    // Wait for server to be in ACTIVE state, before associating floating IP
    try {
        final ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1);
        timer.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                Server checked = IaasOpenstack.this.novaClient.servers().show(server.getId()).execute();
                if ("ACTIVE".equals(checked.getStatus())) {
                    timer.shutdown();
                }
            }
        }, 10, 5, TimeUnit.SECONDS);
        timer.awaitTermination(120, TimeUnit.SECONDS);
    } catch (Exception ignore) {
        /*ignore*/ }

    // Associate floating IP
    if (this.floatingIpPool != null) {
        FloatingIps ips = this.novaClient.floatingIps().list().execute();

        FloatingIp ip = null;
        for (FloatingIp ip2 : ips) {
            System.out.println("ip=" + ip2);
            ip = ip2;
        }
        //FloatingIp ip = ips.allocate(this.floatingIpPool).execute();
        if (ip != null) {
            this.novaClient.servers().associateFloatingIp(server.getId(), ip.getIp()).execute();
        }
    }

    return server.getId();
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkValueRecorder.java

@Override
protected void createHandlerChain() {
    super.createHandlerChain();

    getConnector().addHandler(new DefaultCommandHandler() {
        public boolean handleCommand(BenchmarkCommand command) {
            switch (command.getCommandType()) {
            case CommandTypes.PREPARE_BENCHMARK:
                PrepareBenchmarkCommand prepCmd = (PrepareBenchmarkCommand) command;
                File benchmarkDir = getBenchmarkWorkDirectory(prepCmd.getBenchmarkConfig().getBenchmarkId());
                try {
                    FileUtils.deleteDirectory(benchmarkDir);
                    benchmarkDir.mkdirs();
                } catch (IOException e) {
                    log().error("Error creating directory : " + benchmarkDir.getAbsolutePath(), e);
                    e.printStackTrace();
                }//from  w  w  w .  j av  a2  s. c  o m
                return true;
            case CommandTypes.REPORT_STATS:
                ReportStatsCommand stats = (ReportStatsCommand) command;
                recordStats(stats);
                return true;
            case CommandTypes.END_BENCHMARK:
                EndBenchmarkCommand endCommand = (EndBenchmarkCommand) command;
                final String benchmarkId = endCommand.getBenchmarkId();
                final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
                executor.schedule(new Runnable() {
                    public void run() {
                        for (BenchmarkPostProcessor processor : getPostProcessors()) {
                            processor.resetStatistics();
                            processor.setWorkDir(getBenchmarkWorkDirectory(benchmarkId));
                            processor.processData();
                        }
                        executor.shutdown();
                    }
                }, 5, TimeUnit.SECONDS);
                return true;
            default:
                return false;
            }
        }
    });
}

From source file:org.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception /*from  ww  w .  j  ava  2s  .c  o  m*/
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

    final AtomicReference<Exception> exceptionOnThread = new AtomicReference<Exception>();

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

From source file:org.opendaylight.genius.utils.batching.ResourceBatchingManager.java

public void deregisterBatchableResource(String resourceType) {
    resourceHandlerMapper.remove(resourceType);
    resourceBatchingThreadMapper.remove(resourceType);
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = resourceBatchingThreadMapper.get(resourceType);
    scheduledThreadPoolExecutor.shutdown();
}