List of usage examples for java.util.concurrent ScheduledFuture isCancelled
boolean isCancelled();
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 a2s .c o m*/ 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 w ww . j a v a 2s .c om*/ 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:com.bfd.harpc.heartbeat.HeartBeatManager.java
/** * ?heartbeat// w w w .j av a 2 s . c o m * <p> */ public void stopHeartbeatTimer() { try { ScheduledFuture<?> timer = heatbeatTimer; if (timer != null && !timer.isCancelled()) { timer.cancel(true); } } catch (Throwable t) { LOGGER.warn(t.getMessage(), t); } finally { heatbeatTimer = null; } }
From source file:io.gravitee.gateway.services.healthcheck.HealthCheckService.java
private void stopHealthCheck(Api api) { ScheduledFuture scheduledFuture = scheduledTasks.remove(api); if (scheduledFuture != null) { if (!scheduledFuture.isCancelled()) { LOGGER.info("Stop health-check"); scheduledFuture.cancel(true); } else {/*w ww . j a v a2 s.c o m*/ LOGGER.info("Health-check already shutdown"); } } }
From source file:io.gravitee.gateway.services.apikeyscache.ApiKeysCacheService.java
private void stopRefresher(Api api) { ScheduledFuture scheduledFuture = scheduledTasks.remove(api); if (scheduledFuture != null) { if (!scheduledFuture.isCancelled()) { LOGGER.info("Stop api-keys refresher"); scheduledFuture.cancel(true); } else {/*from ww w. java 2 s. com*/ LOGGER.info("API-key refresher already shutdown"); } } }
From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Updates the task stopping it and rescheduling it * @param task the task to update/*from www .j ava 2s .c o m*/ */ public void updateScheduledTask(ScheduledTaskWrapper task) { if (task == null) { if (log.isTraceEnabled()) { log.trace("Trying to update a null task. Request rejected"); } return; } if (log.isInfoEnabled()) { log.info("Updating task '" + task + "'. The task will be cancelled and " + "then re-scheduled"); } // // Locking the lock for this task so no other thread can handle it avoiding // conflict (what happens if a thread is removing it an another threead is // updating it ?) // Lock handlingTaskLock = getHandlingTaskLock(task.getId()); handlingTaskLock.lock(); try { ScheduledFuture scheduledFuture = null; ScheduledTaskWrapper oldScheduledTask = null; synchronized (scheduledFutures) { scheduledFuture = (ScheduledFuture) scheduledFutures.get(task); oldScheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture); } boolean cancelled = false; if (scheduledFuture != null) { cancelled = scheduledFuture.isCancelled(); if (!cancelled) { cancelled = scheduledFuture.cancel(true); // if we can, we stop its // execution. Remember that // cancel means cancel its // scheduled execution and // not just the running one if (cancelled) { if (log.isTraceEnabled()) { log.trace("Task '" + task.getId() + "' cancelled successfully"); } } else { if (log.isTraceEnabled()) { log.trace("Task '" + task.getId() + "' not cancelled for unknown reasons." + "Is it already cancelled ? " + ((scheduledFuture.isCancelled() ? "YES" : "NO"))); } } } else { if (log.isTraceEnabled()) { log.trace("Task '" + task.getId() + "' has been already cancelled"); } } if (!ScheduledTaskWrapper.State.SHUTDOWN.equals(oldScheduledTask.getState())) { if (log.isTraceEnabled()) { log.trace("Shutting down task '" + task.getId() + "'"); } try { oldScheduledTask.shutdown(); } catch (TaskException ex) { log.error("Error shutting down scheduled task '" + oldScheduledTask + "'", ex); } oldScheduledTask.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(oldScheduledTask); } } else { if (log.isTraceEnabled()) { log.trace("Task '" + task + "' seems not scheduled"); } } scheduleTask(task, 0); } finally { handlingTaskLock.unlock(); } }
From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Called when a ScheduledTask ends its execution. See afterExecute. *//* w w w . j a v a 2s . c o 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.hadoop.security.ssl.TestReloadingX509KeyManager.java
@Test(timeout = 4000) public void testReloadCorruptedKeyStore() throws Exception { KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(KEY_PAIR_ALGORITHM); X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=cert", keyPair, 2, CERTIFICATE_ALGORITHM); String keyStoreLocation = Paths.get(BASE_DIR, "testKeystore.jks").toString(); KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert", keyPair.getPrivate(), cert); ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, KEYSTORE_PASSWORD, KEYSTORE_PASSWORD, 10, TimeUnit.MILLISECONDS); try {//from w ww . j a v a2 s.c o m keyManager.init(); X509Certificate[] certChain = keyManager.getCertificateChain("cert"); assertNotNull("Certificate chain should not be null for alias cert", certChain); keyManager.getReloadTimeUnit().sleep(keyManager.getReloadInterval()); TimeUnit.SECONDS.sleep(1); FileOutputStream outputStream = new FileOutputStream(keyStoreLocation); outputStream.write("something".getBytes()); outputStream.close(); keyManager.getReloadTimeUnit().sleep(keyManager.getReloadInterval()); TimeUnit.SECONDS.sleep(1); certChain = keyManager.getCertificateChain("cert"); assertNotNull("Certificate chain should not be null for alias cert", certChain); assertEquals("DN for cert should be CN=cert", cert.getSubjectDN().getName(), certChain[0].getSubjectDN().getName()); List<ScheduledFuture> reloadTasks = KeyManagersReloaderThreadPool.getInstance(true).getListOfTasks(); // Reloading thread should have been cancelled after unsuccessful reload for (ScheduledFuture task : reloadTasks) { assertTrue(task.isCancelled()); } assertEquals(KeyManagersReloaderThreadPool.MAX_NUMBER_OF_RETRIES + 1, keyManager.getNumberOfFailures()); } finally { keyManager.stop(); } }
From source file:org.apache.hadoop.security.ssl.TestReloadingX509TrustManager.java
@Test(timeout = 30000) public void testReloadCorruptTrustStore() throws Exception { KeyPair kp = generateKeyPair("RSA"); cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA"); cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA"); String truststoreLocation = BASEDIR + "/testcorrupt.jks"; createTrustStore(truststoreLocation, "password", "cert1", cert1); ReloadingX509TrustManager tm = new ReloadingX509TrustManager("jks", truststoreLocation, "password", 10); try {/* w w w . ja va 2 s .co m*/ tm.init(); assertEquals(1, tm.getAcceptedIssuers().length); final X509Certificate cert = tm.getAcceptedIssuers()[0]; // Wait so that the file modification time is different Thread.sleep((tm.getReloadInterval() + 1000)); assertFalse(reloaderLog.getOutput().contains(ReloadingX509TrustManager.RELOAD_ERROR_MESSAGE)); OutputStream os = new FileOutputStream(truststoreLocation); os.write(1); os.close(); waitForFailedReloadAtLeastOnce((int) tm.getReloadInterval()); assertEquals(1, tm.getAcceptedIssuers().length); assertEquals(cert, tm.getAcceptedIssuers()[0]); TimeUnit.SECONDS.sleep(1); List<ScheduledFuture> reloadTasks = KeyManagersReloaderThreadPool.getInstance(true).getListOfTasks(); assertEquals(1, reloadTasks.size()); for (ScheduledFuture task : reloadTasks) { assertTrue(task.isCancelled()); } assertEquals(KeyManagersReloaderThreadPool.MAX_NUMBER_OF_RETRIES + 1, tm.getNumberOfFailures()); } finally { reloaderLog.stopCapturing(); tm.destroy(); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java
@Test public void testCertificateRenewal() throws Exception { conf.set(YarnConfiguration.HOPS_RM_SECURITY_ACTOR_KEY, "org.apache.hadoop.yarn.server.resourcemanager.security.TestingRMAppSecurityActions"); RMAppSecurityManager rmAppSecurityManager = new RMAppSecurityManager(rmContext); MockX509SecurityHandler x509SecurityHandler = new MockX509SecurityHandler(rmContext, rmAppSecurityManager, false);/*from ww w .j a va2s . c o m*/ rmAppSecurityManager.registerRMAppSecurityHandler(x509SecurityHandler); rmAppSecurityManager.init(conf); rmAppSecurityManager.start(); LocalDateTime now = DateUtils.getNow(); LocalDateTime expiration = now.plus(10, ChronoUnit.SECONDS); ApplicationId appId = ApplicationId.newInstance(DateUtils.localDateTime2UnixEpoch(now), 1); x509SecurityHandler.setOldCertificateExpiration(DateUtils.localDateTime2UnixEpoch(expiration)); X509SecurityHandler.X509MaterialParameter x509Param = new X509SecurityHandler.X509MaterialParameter(appId, "Dolores", 1); x509Param.setExpiration(DateUtils.localDateTime2UnixEpoch(expiration)); x509SecurityHandler.registerRenewer(x509Param); Map<ApplicationId, ScheduledFuture> tasks = x509SecurityHandler.getRenewalTasks(); ScheduledFuture renewalTask = tasks.get(appId); assertFalse(renewalTask.isCancelled()); assertFalse(renewalTask.isDone()); // Wait until the scheduled task is executed TimeUnit.SECONDS.sleep(10); assertTrue(renewalTask.isDone()); assertFalse(x509SecurityHandler.getRenewalException()); assertTrue(tasks.isEmpty()); rmAppSecurityManager.stop(); }