Search in sources :

Example 76 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project jdk8u_jdk by JetBrains.

the class DeadSSLLdapTimeoutTest method call.

public Boolean call() {
    InitialContext ctx = null;
    ScheduledFuture killer = null;
    long start = System.nanoTime();
    try {
        while (!server.accepting()) // allow the server to start up
        Thread.sleep(200);
        // to be sure
        Thread.sleep(200);
        env.put(Context.PROVIDER_URL, "ldap://localhost:" + server.getLocalPort());
        try {
            ctx = new InitialDirContext(env);
            performOp(ctx);
            fail();
        } catch (NamingException e) {
            long end = System.nanoTime();
            System.out.println(this.getClass().toString() + " - elapsed: " + NANOSECONDS.toMillis(end - start));
            handleNamingException(e, start, end);
        } finally {
            if (killer != null && !killer.isDone())
                killer.cancel(true);
            shutItDown(ctx);
            server.close();
        }
        return passed;
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 77 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project quorrabot by GloriousEggroll.

the class ScriptApi method setTimeout.

@SuppressWarnings("rawtypes")
public ScheduledFuture<?> setTimeout(Script script, Runnable task, int milliseconds) {
    ScheduledFuture future = scheduler.schedule(task, milliseconds, TimeUnit.MILLISECONDS);
    script.destroyables().add(new ScriptDestroyable<ScheduledFuture>(future) {

        @Override
        public void destroy(ScheduledFuture future) {
            future.cancel(false);
        }
    });
    return future;
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 78 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project samza by apache.

the class ScheduleAfterDebounceTime method scheduleAfterDebounceTime.

public synchronized void scheduleAfterDebounceTime(String actionName, long debounceTimeMs, Runnable runnable) {
    // check if this action has been scheduled already
    ScheduledFuture sf = futureHandles.get(actionName);
    if (sf != null && !sf.isDone()) {
        LOG.info("cancel future for " + actionName);
        // attempt to cancel
        if (!sf.cancel(false)) {
            try {
                sf.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                // we ignore the exception
                LOG.warn("cancel for action " + actionName + " failed with ", e);
            }
        }
        futureHandles.remove(actionName);
    }
    // schedule a new task
    sf = scheduledExecutorService.schedule(() -> {
        try {
            runnable.run();
            LOG.debug(actionName + " completed successfully.");
        } catch (Throwable t) {
            LOG.error(actionName + " threw an exception.", t);
            if (scheduledTaskFailureCallback != null) {
                scheduledTaskFailureCallback.onError(t);
            }
        }
    }, debounceTimeMs, TimeUnit.MILLISECONDS);
    LOG.info("scheduled " + actionName + " in " + debounceTimeMs);
    futureHandles.put(actionName, sf);
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 79 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project flink by apache.

the class JobLeaderIdServiceTest method jobTimeoutAfterLostLeadership.

/**
	 * Tests that a timeout get cancelled once a job leader has been found. Furthermore, it tests
	 * that a new timeout is registered after the jobmanager has lost leadership.
	 */
@Test(timeout = 10000)
public void jobTimeoutAfterLostLeadership() throws Exception {
    final JobID jobId = new JobID();
    final String address = "foobar";
    final UUID leaderId = UUID.randomUUID();
    TestingHighAvailabilityServices highAvailabilityServices = new TestingHighAvailabilityServices();
    TestingLeaderRetrievalService leaderRetrievalService = new TestingLeaderRetrievalService();
    highAvailabilityServices.setJobMasterLeaderRetriever(jobId, leaderRetrievalService);
    ScheduledFuture<?> timeout1 = mock(ScheduledFuture.class);
    ScheduledFuture<?> timeout2 = mock(ScheduledFuture.class);
    final Queue<ScheduledFuture<?>> timeoutQueue = new ArrayDeque<>(Arrays.asList(timeout1, timeout2));
    ScheduledExecutor scheduledExecutor = mock(ScheduledExecutor.class);
    final AtomicReference<Runnable> lastRunnable = new AtomicReference<>();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            lastRunnable.set((Runnable) invocation.getArguments()[0]);
            return timeoutQueue.poll();
        }
    }).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
    Time timeout = Time.milliseconds(5000L);
    JobLeaderIdActions jobLeaderIdActions = mock(JobLeaderIdActions.class);
    final AtomicReference<UUID> lastTimeoutId = new AtomicReference<>();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            lastTimeoutId.set((UUID) invocation.getArguments()[1]);
            return null;
        }
    }).when(jobLeaderIdActions).notifyJobTimeout(eq(jobId), any(UUID.class));
    JobLeaderIdService jobLeaderIdService = new JobLeaderIdService(highAvailabilityServices, scheduledExecutor, timeout);
    jobLeaderIdService.start(jobLeaderIdActions);
    jobLeaderIdService.addJob(jobId);
    Future<UUID> leaderIdFuture = jobLeaderIdService.getLeaderId(jobId);
    // notify the leader id service about the new leader
    leaderRetrievalService.notifyListener(address, leaderId);
    assertEquals(leaderId, leaderIdFuture.get());
    assertTrue(jobLeaderIdService.containsJob(jobId));
    // check that the first timeout got cancelled
    verify(timeout1, times(1)).cancel(anyBoolean());
    verify(scheduledExecutor, times(1)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
    // initial timeout runnable which should no longer have an effect
    Runnable runnable = lastRunnable.get();
    assertNotNull(runnable);
    runnable.run();
    verify(jobLeaderIdActions, times(1)).notifyJobTimeout(eq(jobId), any(UUID.class));
    // the timeout should no longer be valid
    assertFalse(jobLeaderIdService.isValidTimeout(jobId, lastTimeoutId.get()));
    // lose leadership
    leaderRetrievalService.notifyListener("", null);
    verify(scheduledExecutor, times(2)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
    // the second runnable should be the new timeout
    runnable = lastRunnable.get();
    assertNotNull(runnable);
    runnable.run();
    verify(jobLeaderIdActions, times(2)).notifyJobTimeout(eq(jobId), any(UUID.class));
    // the new timeout should be valid
    assertTrue(jobLeaderIdService.isValidTimeout(jobId, lastTimeoutId.get()));
}
Also used : TestingLeaderRetrievalService(org.apache.flink.runtime.leaderelection.TestingLeaderRetrievalService) AtomicReference(java.util.concurrent.atomic.AtomicReference) Time(org.apache.flink.api.common.time.Time) ArrayDeque(java.util.ArrayDeque) ScheduledFuture(java.util.concurrent.ScheduledFuture) ScheduledExecutor(org.apache.flink.runtime.concurrent.ScheduledExecutor) TestingHighAvailabilityServices(org.apache.flink.runtime.highavailability.TestingHighAvailabilityServices) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TimeUnit(java.util.concurrent.TimeUnit) UUID(java.util.UUID) JobID(org.apache.flink.api.common.JobID) Test(org.junit.Test)

Example 80 with ScheduledFuture

use of java.util.concurrent.ScheduledFuture in project samza by apache.

the class TaskCallbackManager method createCallback.

public TaskCallbackImpl createCallback(TaskName taskName, IncomingMessageEnvelope envelope, ReadableCoordinator coordinator) {
    final TaskCallbackImpl callback = new TaskCallbackImpl(listener, taskName, envelope, coordinator, seqNum++, clock.nanoTime());
    if (timer != null) {
        Runnable timerTask = new Runnable() {

            @Override
            public void run() {
                String msg = "Task " + callback.taskName + " callback times out";
                callback.failure(new TaskCallbackTimeoutException(msg));
            }
        };
        ScheduledFuture scheduledFuture = timer.schedule(timerTask, timeout, TimeUnit.MILLISECONDS);
        callback.setScheduledFuture(scheduledFuture);
    }
    return callback;
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture)

Aggregations

ScheduledFuture (java.util.concurrent.ScheduledFuture)85 Test (org.junit.Test)27 Date (java.util.Date)10 DelegatingScheduledFutureStripper (com.hazelcast.scheduledexecutor.impl.DelegatingScheduledFutureStripper)9 ParallelTest (com.hazelcast.test.annotation.ParallelTest)9 QuickTest (com.hazelcast.test.annotation.QuickTest)9 IOException (java.io.IOException)8 Map (java.util.Map)7 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)7 TimeValue (org.elasticsearch.common.unit.TimeValue)6 None (com.linkedin.common.util.None)5 D2Client (com.linkedin.d2.balancer.D2Client)5 D2ClientBuilder (com.linkedin.d2.balancer.D2ClientBuilder)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 JSONObject (org.json.simple.JSONObject)5 IdleReaderException (com.twitter.distributedlog.exceptions.IdleReaderException)4 Future (java.util.concurrent.Future)4 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)4