Example usage for java.util.concurrent ScheduledFuture cancel

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

Introduction

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

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

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/*www . j av  a  2 s. co 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:org.apache.synapse.transport.amqp.pollingtask.AMQPTransportPollingTask.java

/**
 * Stop the polling tasks//  www  .  j ava2 s . c  o  m
 */
public synchronized void stop() {
    for (ScheduledFuture<?> pollingTaskFuture : taskFutureList) {
        pollingTaskFuture.cancel(false);
    }
}

From source file:com.l2jfree.gameserver.instancemanager.AutoSpawnManager.java

public void reload() {
    // stop all timers
    for (ScheduledFuture<?> sf : _runningSpawns.values()) {
        if (sf != null)
            sf.cancel(true);
    }//from ww w. j a v a  2s.c  om
    // unregister all registered spawns
    for (AutoSpawnInstance asi : _registeredSpawns.values()) {
        if (asi != null)
            this.removeSpawn(asi);
    }

    // create clean list
    _registeredSpawns = new FastMap<Integer, AutoSpawnInstance>();
    _runningSpawns = new FastMap<Integer, ScheduledFuture<?>>();

    // load
    restoreSpawnData();
}

From source file:io.openvidu.server.recording.service.RecordingManager.java

public boolean abortAutomaticRecordingStopThread(Session session) {
    ScheduledFuture<?> future = this.automaticRecordingStopThreads.remove(session.getSessionId());
    if (future != null) {
        boolean cancelled = future.cancel(false);
        if (session.getParticipants().size() == 0 || (session.getParticipants().size() == 1
                && session.getParticipantByPublicId(ProtocolElements.RECORDER_PARTICIPANT_PUBLICID) != null)) {
            // Close session if there are no participants connected (except for RECORDER).
            // This code will only be executed if recording is manually stopped during the
            // automatic stop timeout, so the session must be also closed
            log.info(// ww  w .  j av a2 s. c  om
                    "Ongoing recording of session {} was explicetly stopped within timeout for automatic recording stop. Closing session",
                    session.getSessionId());
            sessionManager.closeSessionAndEmptyCollections(session, EndReason.automaticStop);
            sessionManager.showTokens();
        }
        return cancelled;
    } else {
        return true;
    }
}

From source file:com.l2jfree.gameserver.instancemanager.AutoSpawnManager.java

/**
 * Remove a registered spawn from the list, specified by the given spawn instance.
 * /*from w  w w  . j  a v a2  s  . c  o m*/
 * @param spawnInst
 * @return boolean removedSuccessfully
 */
public boolean removeSpawn(AutoSpawnInstance spawnInst) {
    if (!isSpawnRegistered(spawnInst))
        return false;

    try {
        // Try to remove from the list of registered spawns if it exists.
        _registeredSpawns.remove(spawnInst.getNpcId());

        // Cancel the currently associated running scheduled task.
        ScheduledFuture<?> respawnTask = _runningSpawns.remove(spawnInst._objectId);
        if (respawnTask != null)
            respawnTask.cancel(false);

        if (_log.isDebugEnabled())
            _log.debug("AutoSpawnHandler: Removed auto spawn for NPC ID " + spawnInst._npcId + " (Object ID = "
                    + spawnInst._objectId + ").");
    } catch (Exception e) {
        _log.warn("AutoSpawnHandler: Could not auto spawn for NPC ID " + spawnInst._npcId + " (Object ID = "
                + spawnInst._objectId + "): ", e);
        return false;
    }

    return true;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

public void deregisterFromCertificateRenewer(ApplicationId appId) {
    if (!isHopsTLSEnabled()) {
        return;//from  w  ww. j  a  v  a 2  s  .com
    }
    ScheduledFuture task = renewalTasks.remove(appId);
    if (task != null) {
        task.cancel(true);
    }
}

From source file:io.tilt.minka.business.impl.CoordinatorImpl.java

private void stop(final Synchronized synchro, final boolean withFire) {
    Validate.notNull(synchro);/*  w  w w  . j a va2  s  .c  o m*/
    final Callable<?> callable = this.callablesBySynchro.get(synchro);
    final Runnable runnable = this.runnablesBySynchro.get(synchro);
    ScheduledFuture<?> future = this.futuresBySynchro.get(synchro);
    boolean dequeued = false;

    if (runnable != null) {
        runnablesBySynchro.remove(synchro);
        dequeued = this.executor.remove(runnable);
    } else if (callable != null) {
        callablesBySynchro.remove(synchro);
    } else {
        logger.error("{}: ({}) Runnable/Callable {} not found, finished or never scheduled",
                getClass().getSimpleName(), shardId, synchro.getAction().name());
        return;
    }

    if (future != null) {
        boolean cancelled = future.cancel(withFire);
        logger.debug("{}: ({}) Stopping - Task {} ({}) Cancelled = {}, Dequeued = {}",
                getClass().getSimpleName(), shardId, synchro.getAction().name(),
                runnable.getClass().getSimpleName(), cancelled, dequeued);
    } else {
        logger.error("{}: ({}) Stopping - Task {} ({}) Not found !!", getClass().getSimpleName(), shardId,
                synchro.getAction().name(), runnable.getClass().getSimpleName());
    }
    this.executor.purge();
    agentsByAction.remove(synchro.getAction());
}

From source file:org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler.java

private void cleanup() {
    logger.debug("cleanup {}", getThing().getUID().getAsString());
    @Nullable
    ScheduledFuture<?> refreshJob = this.checkDataJob;
    if (refreshJob != null) {
        refreshJob.cancel(true);
        this.checkDataJob = null;
    }//from  w  w w. ja  v a  2  s.  c o m
    @Nullable
    ScheduledFuture<?> refreshLogin = this.checkLoginJob;
    if (refreshLogin != null) {
        refreshLogin.cancel(true);
        this.checkLoginJob = null;
    }
    @Nullable
    ScheduledFuture<?> foceCheckDataJob = this.foceCheckDataJob;
    if (foceCheckDataJob != null) {
        foceCheckDataJob.cancel(true);
        this.foceCheckDataJob = null;
    }
    @Nullable
    ScheduledFuture<?> refreshDataDelayed = this.refreshAfterCommandJob;
    if (refreshDataDelayed != null) {
        refreshDataDelayed.cancel(true);
        this.refreshAfterCommandJob = null;
    }
    Connection connection = this.connection;
    if (connection != null) {
        connection.logout();
        this.connection = null;
    }
    closeWebSocketConnection();
}

From source file:io.fabric8.kubernetes.client.dsl.internal.RollingUpdater.java

/**
 * Since k8s v1.4.x, rc/rs deletes are asynchronous.
 * Lets wait until the resource is actually deleted in the server
 *///from w w  w.j a  va2  s  .c o m
private void waitUntilDeleted(final String namespace, final String name) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);

    final Runnable waitTillDeletedPoller = new Runnable() {
        public void run() {
            try {
                T res = resources().inNamespace(namespace).withName(name).get();
                if (res == null) {
                    countDownLatch.countDown();
                }
            } catch (KubernetesClientException e) {
                if (e.getCode() == 404) {
                    countDownLatch.countDown();
                }
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
    ScheduledFuture logger = executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name);
        }
    }, 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
    try {
        countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
        executor.shutdown();
    } catch (InterruptedException e) {
        poller.cancel(true);
        logger.cancel(true);
        executor.shutdown();
        LOG.warn("Still found deleted resource {} in namespace: {}  after waiting for {} seconds so giving up",
                name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
    }
}

From source file:org.openhab.binding.amazonechocontrol.handler.EchoHandler.java

@Override
public void dispose() {
    stopCurrentNotification();// w ww  .j  a va  2  s  .  c o m
    ScheduledFuture<?> updateStateJob = this.updateStateJob;
    this.updateStateJob = null;
    if (updateStateJob != null) {
        updateStateJob.cancel(false);
    }
    super.dispose();
}