Example usage for java.util.concurrent ScheduledFuture isDone

List of usage examples for java.util.concurrent ScheduledFuture isDone

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledFuture isDone.

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

From source file:com.pushtechnology.consulting.Benchmarker.java

public static void main(String[] args) throws InterruptedException {
    LOG.info("Starting Java Benchmark Suite v{}", Benchmarker.class.getPackage().getImplementationVersion());

    final Arguments arguments = Arguments.parse(args);

    try {//from w  w  w. j  a  v a 2 s .  c  om
        LOG.debug("Trying to set client InboundThreadPool queue size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        final ThreadsConfig threadsConfig = ConfigManager.getConfig().getThreads();
        final ThreadPoolConfig inboundPool = threadsConfig.addPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        inboundPool.setQueueSize(CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        inboundPool.setCoreSize(CLIENT_INBOUND_QUEUE_CORE_SIZE);
        inboundPool.setMaximumSize(CLIENT_INBOUND_QUEUE_MAX_SIZE);
        threadsConfig.setInboundPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        LOG.debug("Successfully set client InboundThreadPool queue size to '{}'",
                CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
    } catch (APIException ex) {
        LOG.error("Failed to set client inbound pool size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        ex.printStackTrace();
    }

    connectThreadPool = Executors.newScheduledThreadPool(arguments.connectThreadPoolSize);
    final Publisher publisher;

    if (arguments.doPublish) {
        LOG.info("Creating Publisher with connection string: '{}'", arguments.publisherConnectionString);
        publisher = new Publisher(arguments.publisherConnectionString, arguments.publisherUsername,
                arguments.publisherPassword, arguments.topics, arguments.topicType);
        publisher.start();

        publisherMonitor = globalThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LOG.trace("publisherMonitor fired");
                LOG.info("There are {} publishers running for topics: '{}'",
                        publisher.getUpdaterFuturessByTopic().size(),
                        ArrayUtils.toString(publisher.getUpdaterFuturessByTopic().keySet()));
                for (ScheduledFuture<?> svc : publisher.getUpdaterFuturessByTopic().values()) {
                    if (svc.isCancelled()) {
                        LOG.debug("Service is cancelled...");
                    }
                    if (svc.isDone()) {
                        LOG.debug("Service is done...");
                    }
                }
                LOG.trace("Done publisherMonitor fired");
            }
        }, 2L, 5L, SECONDS);
    } else {
        publisher = null;
    }

    /* Create subscribing sessions. Finite or churning */
    if (arguments.doCreateSessions) {
        if (arguments.maxNumSessions > 0) {
            LOG.info("Creating {} Sessions with connection string: '{}'", arguments.maxNumSessions,
                    arguments.sessionConnectionString);
        } else {
            LOG.info("Creating Sessions with connection string: '{}s'", arguments.sessionConnectionString);
            LOG.info("Creating Sessions at {}/second, disconnecting after {} seconds", arguments.sessionRate,
                    arguments.sessionDuration);
        }
        sessionCreator = new SessionCreator(arguments.sessionConnectionString, arguments.myTopics,
                arguments.topicType);

        LOG.info(
                "Sessions: [Connected] [Started] [Recovering] [Closed] [Ended] [Failed]  | Messages: [Number] [Bytes]");
        sessionsCounter = globalThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LOG.trace("sessionsCounter fired");
                LOG.info("Sessions: {} {} {} {} {} {} | Messages: {} {}",
                        sessionCreator.getConnectedSessions().get(), sessionCreator.getStartedSessions().get(),
                        sessionCreator.getRecoveringSessions().get(), sessionCreator.getClosedSessions().get(),
                        sessionCreator.getEndedSessions().get(), sessionCreator.getConnectionFailures().get(),
                        sessionCreator.getMessageCount().getAndSet(0),
                        sessionCreator.getMessageByteCount().getAndSet(0));
                LOG.trace("Done sessionsCounter fired");
            }
        }, 0L, 5L, SECONDS);

        if (arguments.maxNumSessions > 0) {
            sessionCreator.start(arguments.maxNumSessions);
        } else {
            sessionCreator.start(arguments.sessionRate, arguments.sessionDuration);
        }
    }

    RUNNING_LATCH.await();

    if (arguments.doPublish) {
        if (publisher != null) {
            publisher.shutdown();
        }
        publisherMonitor.cancel(false);
    }

    if (arguments.doCreateSessions) {
        sessionCreator.shutdown();
        sessionsCounter.cancel(false);
    }

    if (!globalThreadPool.isTerminated()) {
        try {
            globalThreadPool.awaitTermination(1L, SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.bt.aloha.util.CollectionHelper.java

public static void destroy(ConcurrentMap<String, Map<String, Object>> transients, String classname) {
    log.debug(String.format("Destroy method called on collection: %s", classname));
    for (Map<String, Object> element : transients.values()) {
        ScheduledFuture<?> future = (ScheduledFuture<?>) element.get("future");
        if (future == null || future.isCancelled() || future.isDone())
            continue;
        if (future.getDelay(TimeUnit.MILLISECONDS) > ONE_HUNDRED) {
            future.cancel(true);/*from ww  w  .  java 2s  .  com*/
            continue;
        }
        int counter = 0;
        while (!future.isDone() && counter++ < THREE) {
            try {
                log.debug("Waiting for future to get done for some call...");
                Thread.sleep(ONE_THOUSAND);
            } catch (InterruptedException e) {
                log.warn(e.getMessage());
                continue;
            }
        }
    }
}

From source file:org.openengsb.opencit.core.projectmanager.internal.SchedulingServiceImpl.java

@Override
public boolean isProjectPolling(String projectid) {
    if (!pollFutures.containsKey(projectid)) {
        return false;
    }//from   ww  w. j a  va2s.c  o  m
    ScheduledFuture<?> future = pollFutures.get(projectid);
    return !future.isDone();
}

From source file:io.fabric8.che.starter.openshift.CheDeploymentConfig.java

private void waitUntilDeploymentConfigIsAvailable(final OpenShiftClient client, String namespace) {
    final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);

    final Runnable readinessPoller = new Runnable() {
        public void run() {
            try {
                if (isDeploymentAvailable(client, namespace)) {
                    queue.put(true);//from   ww  w .j  av  a 2s . c  om
                    return;
                } else {
                    queue.put(false);
                    return;
                }
            } catch (Throwable t) {
                try {
                    if (queue.isEmpty()) {
                        queue.put(false);
                    }
                    return;
                } catch (InterruptedException e) {
                }
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> poller = executor.scheduleWithFixedDelay(readinessPoller, 0, 500, TimeUnit.MILLISECONDS);
    executor.schedule(new Runnable() {

        @Override
        public void run() {
            poller.cancel(true);
        }
    }, Integer.valueOf(startTimeout), TimeUnit.SECONDS);
    try {
        while (!waitUntilReady(queue)) {
        }
    } finally {
        if (!poller.isDone()) {
            poller.cancel(true);
        }
        executor.shutdown();
    }
}

From source file:com.magnet.mmx.util.AlertEventsManagerTest.java

public void testInterEmailTime() {
    setupMocks();/* w w w .  j a  v a  2s  .  c om*/
    long testDurationMinutes = 5;
    MMXConfiguration.getConfiguration().setValue(MMXConfigKeys.ALERT_EMAIL_ENABLED, "true");
    MMXConfiguration.getConfiguration().setValue(MMXConfigKeys.ALERT_INTER_EMAIL_TIME_MINUTES, "1");
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
    ScheduledFuture<?> future = executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            AlertEventsManager.post(getRandomEvent());
        }
    }, 0L, 500, TimeUnit.MILLISECONDS);
    List<ScheduledFuture<?>> list = new ArrayList<ScheduledFuture<?>>();
    list.add(future);
    executorService.schedule(new StopTestTask(list), testDurationMinutes, TimeUnit.MINUTES);
    while (!future.isDone())
        ;
    LOGGER.trace("testInterEmailTime : average inter email time = {}", getAvg(elapsedTimes));
}

From source file:com.netflix.genie.web.tasks.job.JobMonitoringCoordinatorUnitTests.java

/**
 * Make sure we can kill the job init task on job finished event for the job.
 *
 * @throws GenieException on error/*from w  w w .j  a  v  a 2s . c o m*/
 */
@Test
public void canStopJobTask() throws GenieException {
    final String jobId = UUID.randomUUID().toString();
    final ScheduledFuture task = Mockito.mock(ScheduledFuture.class);
    final JobFinishedEvent jobFinishedEvent = new JobFinishedEvent(jobId, JobFinishedReason.FAILED_TO_INIT,
            "something", this);
    Mockito.when(task.isDone()).thenReturn(true).thenReturn(false).thenReturn(false);
    Mockito.when(task.cancel(true)).thenReturn(true).thenReturn(false);
    Mockito.when(scheduler.schedule(Mockito.any(), Mockito.any(Date.class))).thenReturn(task);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(jobId);
    coordinator.schedule(jobId, null, null, null, null, 1024);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(jobFinishedEvent);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(jobId);
    coordinator.schedule(jobId, null, null, null, null, 1024);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(jobFinishedEvent);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(jobId);
    coordinator.schedule(jobId, null, null, null, null, 1024);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(jobFinishedEvent);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));

    Mockito.verify(this.unableToCancel, Mockito.times(1)).increment();
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * If there is, logs the exception thrown by the taskWrapper execution
 * @param taskWrapper the executed task wrapper
 * @param scheduledFuture the scheduledFuture with the exception (if there is)
 *///w w w  .  j av a  2 s  . c  om
private void logTaskWrapperExecutionError(TaskWrapper taskWrapper, ScheduledFuture scheduledFuture) {
    try {
        if (scheduledFuture.isDone()) {
            scheduledFuture.get();
        }
    } catch (InterruptedException ie) {
    } catch (ExecutionException ee) {
        //
        // This is done to retrieve the possible exception thrown by the
        // task
        //
        Throwable realThrowable = ee.getCause();

        if (taskWrapper != null) {
            log.error("Task '" + taskWrapper + "' throws an uncaught exception. ", realThrowable);
        } else {
            log.error("Uncaught exception thrown by: " + scheduledFuture, realThrowable);
        }
    }
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Called when a ScheduledTask ends its execution. See afterExecute.
 *///from ww w  . j av a 2  s .  co m
protected void afterScheduledTaskExecution(Runnable r, Throwable t) {
    super.afterExecute(r, t);

    ScheduledTaskWrapper scheduledTask = null;
    Lock handlingTaskLock = null;

    if (r instanceof ScheduledFuture) {
        ScheduledFuture scheduledFuture = (ScheduledFuture) r;
        synchronized (scheduledFutures) {
            scheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture);

            if (scheduledTask != null) {
                handlingTaskLock = getHandlingTaskLock(scheduledTask.getId());
                handlingTaskLock.lock();
            }
        }
        //
        // Bear in mind that here the scheduledTask could be null if the scheduledFuture
        // has been cancelled and removed from the scheduledFutures map.
        //
        if (log.isTraceEnabled()) {
            if (scheduledTask == null) {
                log.trace("Scheduled task null for: " + r + ". Is it cancelled ? "
                        + scheduledFuture.isCancelled());
            }
        }

        try {
            if (scheduledFuture.isDone()) {
                scheduledFuture.get();
            }
        } catch (InterruptedException ie) {
        } catch (ExecutionException ee) {
            //
            // This is done to retrieve the possible exception thrown by the
            // task
            //
            Throwable realThrowable = ee.getCause();

            if (scheduledTask != null) {

                log.error("Task '" + scheduledTask + "' throws an uncaught exception. "
                        + "The task will be rescheduled", realThrowable);
                try {
                    scheduledTask.shutdown();
                } catch (TaskException ex) {
                    log.error("Error shutting down scheduled task '" + scheduledTask + "'", ex);
                }

                scheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN);

                synchronized (scheduledFutures) {
                    //
                    // Any time we remove the scheduledTask from scheduledFutures,
                    // we try to remove the scheduledFuture from the queue. This
                    // is not really needed because after a while this is performed
                    // automatically but in this way we keep scheduledFutures and
                    // the queue in sync
                    //
                    if (scheduledFuture instanceof Runnable) {
                        super.remove((Runnable) scheduledFuture);
                    }
                    scheduledFutures.remove(scheduledTask);
                }

                //
                // The task will be rescheduled using the period as delay
                // because otherwise a new execution is performed asap
                //
                scheduleTask(scheduledTask, scheduledTask.getPeriod());

            } else {
                log.error("Uncaught exception thrown by: " + scheduledFuture
                        + ". This ScheduledFuture seems not relative to a ScheduleTask"
                        + " so nothing will be rescheduled (it could be about "
                        + " to an already cancelled task)", realThrowable);
            }

        } catch (CancellationException ce) {
        } finally {
            if (handlingTaskLock != null) {
                handlingTaskLock.unlock();
            }
            handlingScheduledExecutionTimeInformation(scheduledTask);
            LogContext.clear();
        }
    }
}

From source file:org.apache.distributedlog.BKLogSegmentWriter.java

void scheduleFlushWithDelayIfNeeded(final Callable<?> callable,
        final AtomicReferenceFieldUpdater<BKLogSegmentWriter, ScheduledFuture> scheduledFutureRefUpdater) {
    final long delayMs = Math.max(0,
            minDelayBetweenImmediateFlushMs - lastTransmit.elapsed(TimeUnit.MILLISECONDS));
    final ScheduledFuture scheduledFuture = scheduledFutureRefUpdater.get(this);
    if ((null == scheduledFuture) || scheduledFuture.isDone()) {
        scheduledFutureRefUpdater.set(this, scheduler.schedule(new Runnable() {
            @Override/*from   www  .  j ava 2 s .  c  o  m*/
            public void run() {
                synchronized (this) {
                    scheduledFutureRefUpdater.set(BKLogSegmentWriter.this, null);
                    try {
                        callable.call();

                        // Flush was successful or wasn't needed, the exception should be unset.
                        scheduledFlushExceptionUpdater.set(BKLogSegmentWriter.this, null);
                    } catch (Exception exc) {
                        scheduledFlushExceptionUpdater.set(BKLogSegmentWriter.this, exc);
                        LOG.error("Delayed flush failed", exc);
                    }
                }
            }
        }, delayMs, TimeUnit.MILLISECONDS));
    }
}