Example usage for java.util.concurrent ScheduledThreadPoolExecutor awaitTermination

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

Introduction

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

Prototype

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

Source Link

Usage

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  w w  w. j  av a  2  s. co 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: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  w w . j  av a2  s  .  c o  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:org.elasticsearch.client.sniff.SnifferTests.java

public void testDefaultSchedulerShutdown() throws Exception {
    ScheduledThreadPoolExecutor executor = mock(ScheduledThreadPoolExecutor.class);
    DefaultScheduler defaultScheduler = new DefaultScheduler(executor);
    defaultScheduler.shutdown();//from w  w  w  . java2s. co  m
    verify(executor).shutdown();
    verify(executor).awaitTermination(1000, TimeUnit.MILLISECONDS);
    verify(executor).shutdownNow();
    verifyNoMoreInteractions(executor);

    when(executor.awaitTermination(1000, TimeUnit.MILLISECONDS)).thenReturn(true);
    defaultScheduler.shutdown();
    verify(executor, times(2)).shutdown();
    verify(executor, times(2)).awaitTermination(1000, TimeUnit.MILLISECONDS);
    verifyNoMoreInteractions(executor);
}

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  w  w  w.ja v  a 2  s . 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();
    }
}