public void stop() { try { if (start.compareAndSet(true, false)) { scheduledFuture.cancel(true); channelCheckExecutorService.shutdown(); offlineTaskTrackerScheduledFuture.cancel(true); offlineTaskTrackerCheckExecutorService.shutdown(); } LOGGER.info("Stop channel manager success!"); } catch (Throwable t) { LOGGER.error("Stop channel manager failed!", t); } }
private void stopTimeoutMonitor() { timeoutLock.lock(); try { if (timeoutFuture != null && activeInstances.size() != 0 && timeoutFuture.cancel(false)) { timeoutFutureRef.set(null); LOG.info("Stopped timeout monitor task"); } else { LOG.info("Timeout monitor task not stopped. Timeout future state: {}, #instances: {}", timeoutFuture == null ? "null" : timeoutFuture.isDone(), activeInstances.size()); } timeoutFuture = null; } finally { timeoutLock.unlock(); } }
public static void cancelScheduledFuture(ScheduledFuture<?> scheduledFuture) { ScheduledFuture<?> future = scheduledFuture; if (future != null && !future.isCancelled()) { future.cancel(true); } } }
/** * Start the scan task for long-idle connections. */ private synchronized void startScan() { if (scanTaskFuture == null || scanTaskFuture.isCancelled() || scanTaskFuture.isDone()) { scanTaskFuture = TIMER.scheduleAtFixedRate( new ScanIdleConnectionTask(this), 10, 30, TimeUnit.SECONDS); } }
private void waitForObservedGeneration(final long observedGeneration) { final CountDownLatch countDownLatch = new CountDownLatch(1); final Runnable deploymentPoller = new Runnable() { public void run() { Deployment deployment = oper.getMandatory(); if (observedGeneration <= deployment.getStatus().getObservedGeneration()) { countDownLatch.countDown(); } } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture poller = executor.scheduleWithFixedDelay(deploymentPoller, 0, 10, TimeUnit.MILLISECONDS); try { countDownLatch.await(1, TimeUnit.MINUTES); executor.shutdown(); } catch (InterruptedException e) { poller.cancel(true); executor.shutdown(); throw KubernetesClientException.launderThrowable(e); } }
final AtomicReference<Integer> replicasRef = new AtomicReference<>(0); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture poller = executor.scheduleWithFixedDelay(tPoller, 0, POLL_INTERVAL_MS, TimeUnit.MILLISECONDS); try { if (Utils.waitUntilReady(queue, rollingTimeout, rollingTimeUnit)) { Log.debug("{}/{} pod(s) ready for {}: {} in namespace: {}.", replicasRef.get(), count, getType().getSimpleName(), name, namespace); } else { Log.error("{}/{} pod(s) ready for {}: {} in namespace: {} after waiting for {} seconds so giving up", replicasRef.get(), count, getType().getSimpleName(), name, namespace, rollingTimeUnit.toSeconds(rollingTimeout)); poller.cancel(true); executor.shutdown();
final CountDownLatch countDownLatch = new CountDownLatch(1); final AtomicReference<Job> atomicJob = new AtomicReference<>(); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture poller = executor.scheduleWithFixedDelay(jobPoller, 0, POLL_INTERVAL_MS, TimeUnit.MILLISECONDS); try { countDownLatch.await(getConfig().getScaleTimeout(), TimeUnit.MILLISECONDS); executor.shutdown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); poller.cancel(true); executor.shutdown(); LOG.error("Only {}/{} pod(s) ready for Job: {} in namespace: {} - giving up", atomicJob.get().getStatus().getActive(), atomicJob.get().getSpec().getParallelism(), atomicJob.get().getMetadata().getName(), namespace);
/** * For JMX to forget about all previously exported metrics. */ public static void clearJmxCache() { if (LOG.isTraceEnabled()) { LOG.trace("clearing JMX Cache" + StringUtils.stringifyException(new Exception())); } //If there are more then 100 ms before the executor will run then everything should be merged. ScheduledFuture future = fut.get(); if ((future != null && (!future.isDone() && future.getDelay(TimeUnit.MILLISECONDS) > 100))) { // BAIL OUT return; } if (stopped.get()) { return; } future = executor.getExecutor().schedule(new JmxCacheBusterRunnable(), 5, TimeUnit.SECONDS); fut.set(future); }
/** * Blocks until the Elasticsearch cluster and current write index is healthy again or the given timeout fires. * * @param timeout the timeout value * @param unit the timeout unit * @throws InterruptedException * @throws TimeoutException */ public void waitForConnectedAndDeflectorHealthy(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { LOG.debug("Waiting until the write-active index is healthy again, checking once per second."); final CountDownLatch latch = new CountDownLatch(1); final ScheduledFuture<?> scheduledFuture = scheduler.scheduleAtFixedRate(() -> { try { if (isConnected() && isDeflectorHealthy()) { LOG.debug("Write-active index is healthy again, unblocking waiting threads."); latch.countDown(); } } catch (Exception ignore) { } // to not cancel the schedule }, 0, 1, TimeUnit.SECONDS); // TODO should this be configurable? final boolean waitSuccess = latch.await(timeout, unit); scheduledFuture.cancel(true); // Make sure to cancel the task to avoid task leaks! if (!waitSuccess) { throw new TimeoutException("Write-active index didn't get healthy within timeout"); } }
future = s.schedule(r, randomTimeout(), randomTimeUnit()); assertFalse(future.isDone()); if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); assertSame(p, recorder.p); future = s.schedule(c, randomTimeout(), randomTimeUnit()); assertFalse(future.isDone()); if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); assertSame(p, recorder.p); future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); assertFalse(future.isDone()); if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); assertSame(p, recorder.p); future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS); assertFalse(future.isDone()); if (stock) assertTrue(!((FutureTask) recorder.r).isDone()); assertSame(p, recorder.p); final AtomicReference<Thread> thread = new AtomicReference<>(); final Runnable setThread = () -> thread.set(Thread.currentThread()); shouldThrow(); } catch (RejectedExecutionException success) {} assertNull(thread.get());
final AtomicBoolean done = new AtomicBoolean(); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture<?> timer = executorService.schedule(new Runnable() { @Override public void run() { } finally { synchronized (monitor) { done.set(true); timer.cancel(true); executorService.shutdownNow();
/** * Stops the clearing of JMX metrics and restarting the Hadoop metrics system. This is needed for * some test environments where we manually inject sources or sinks dynamically. */ @VisibleForTesting public static void stop() { stopped.set(true); ScheduledFuture future = fut.get(); future.cancel(false); }
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void receiptNotReceived() { TaskScheduler taskScheduler = mock(TaskScheduler.class); this.session.afterConnected(this.connection); this.session.setTaskScheduler(taskScheduler); AtomicReference<Boolean> notReceived = new AtomicReference<>(); ScheduledFuture future = mock(ScheduledFuture.class); when(taskScheduler.schedule(any(Runnable.class), any(Date.class))).thenReturn(future); StompHeaders headers = new StompHeaders(); headers.setDestination("/topic/foo"); headers.setReceipt("my-receipt"); Receiptable receiptable = this.session.send(headers, "payload"); receiptable.addReceiptLostTask(() -> notReceived.set(true)); ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class); verify(taskScheduler).schedule(taskCaptor.capture(), (Date) notNull()); Runnable scheduledTask = taskCaptor.getValue(); assertNotNull(scheduledTask); assertNull(notReceived.get()); scheduledTask.run(); assertTrue(notReceived.get()); verify(future).cancel(true); verifyNoMoreInteractions(future); }
@SuppressWarnings("rawtypes") @Ignore("why test JDK feature?") @Test public void testSchedulerPool() throws InterruptedException { logger.info("testSchedulerPool"); ScheduledExecutorService fetchPool = Executors.newScheduledThreadPool(1); final CountDownLatch countDownLatch = new CountDownLatch(3); ScheduledFuture future = fetchPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { countDownLatch.countDown(); } }, 0, 1, TimeUnit.SECONDS); assertTrue("countDownLatch should reach zero in 15 secs", countDownLatch.await(7, TimeUnit.SECONDS)); assertTrue("future should still running", future.cancel(true)); final CountDownLatch countDownLatch2 = new CountDownLatch(3); ScheduledFuture future2 = fetchPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { countDownLatch2.countDown(); throw new RuntimeException(); } }, 0, 1, TimeUnit.SECONDS); assertFalse("countDownLatch2 should NOT reach zero in 15 secs", countDownLatch2.await(7, TimeUnit.SECONDS)); assertFalse("future2 should has been stopped", future2.cancel(true)); }
final AtomicReference<Throwable> errorRef = new AtomicReference<>(); future.cancel(true); if (errorRef.get() != null) { throw new Exception(errorRef.get());
@Test @Description("Tests that a ScheduledFuture is properly cancelled for a fixed-rate Callable before it starts executing") public void cancelFixedRateBeforeFire() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final ScheduledFuture<?> scheduled = executor.scheduleAtFixedRate(() -> { awaitLatch(latch); }, SECONDS.toMillis(DEFAULT_TEST_TIMEOUT_SECS), 10 * TEST_DELAY_MILLIS, MILLISECONDS); scheduled.cancel(true); assertCancelled(scheduled); assertTerminationIsNotDelayed(executor); }
public void reschedule(long timeOut, TimeUnit timeUnit) { ScheduledFuture<?> future = reference.getAndSet(null); if (future != null) { if (future.cancel(false)) { future = service.schedule(task, timeOut == 0 ? Integer.MAX_VALUE : timeOut, timeOut == 0 ? TimeUnit.SECONDS : timeUnit); reference.set(future); } } else { future = service.schedule(task, timeOut == 0 ? Integer.MAX_VALUE : timeOut, timeOut == 0 ? TimeUnit.SECONDS : timeUnit); reference.set(future); } } }