Example usage for java.util.concurrent Future cancel

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

Introduction

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

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:org.pentaho.reporting.platform.plugin.JobManager.java

@SuppressWarnings("unchecked")
@GET//w ww .  ja v  a  2s . c  o m
@Path("{job_id}/cancel")
public Response cancel(@PathParam("job_id") final String jobId) {
    try {

        final ExecutionContext context = getContext(jobId);

        final Future<InputStream> future = context.getFuture();
        final IAsyncReportState state = context.getReportState();

        logger.debug("Cancellation of report: " + state.getPath() + ", requested by : " + context.getSession());

        future.cancel(true);

        return Response.ok().build();
    } catch (final ContextFailedException e) {
        return get404();
    } catch (final FutureNotFoundException e) {
        return Response.ok().build();
    }
}

From source file:org.objectweb.proactive.extensions.dataspaces.vfs.VFSMountManagerHelper.java

/**
 * tries to close the FileSystems represented by the given urls
 *
 * @param uris file system uris/*from   w ww.j  a v  a 2 s.  c  o  m*/
 */
public static void closeFileSystems(Collection<String> uris) {
    try {
        writeLock.lock();
        for (String uri : uris) {
            if (alreadyMountedSpaces.containsKey(uri)) {
                Future<FileObject> future = alreadyMountedSpaces.remove(uri);
                if (future.isDone()) {

                    try {
                        FileObject fo = future.get();
                        final FileSystem spaceFileSystem = fo.getFileSystem();

                        // we may not need to close FileObject, but with VFS you never know...
                        try {
                            fo.close();
                        } catch (org.apache.commons.vfs.FileSystemException x) {
                            logger.debug("Could not close data space root file object : " + fo, x);
                            ProActiveLogger.logEatedException(logger,
                                    String.format("Could not close data space %s root file object", fo), x);
                        }
                        vfsManager.closeFileSystem(spaceFileSystem);
                        if (logger.isDebugEnabled())
                            logger.debug("Unmounted space: " + fo);
                    } catch (InterruptedException e) {
                        // ignore
                    } catch (ExecutionException e) {
                        // ignore
                    }
                } else {
                    future.cancel(true);
                }
            }
        }
    } finally {
        writeLock.unlock();
    }
}

From source file:org.apache.syncope.core.provisioning.java.ConnectorFacadeProxy.java

@Override
public Uid update(final ObjectClass objectClass, final Uid uid, final Set<Attribute> attrs,
        final OperationOptions options, final Boolean[] propagationAttempted) {

    Uid result = null;/*from   w  w w.  j  ava 2 s . c  o  m*/

    if (connInstance.getCapabilities().contains(ConnectorCapability.UPDATE)) {
        propagationAttempted[0] = true;

        Future<Uid> future = asyncFacade.update(connector, objectClass, uid, attrs, options);

        try {
            result = future.get(connInstance.getConnRequestTimeout(), TimeUnit.SECONDS);
        } catch (java.util.concurrent.TimeoutException e) {
            future.cancel(true);
            throw new TimeoutException("Request timeout");
        } catch (Exception e) {
            LOG.error("Connector request execution failure", e);
            if (e.getCause() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            } else {
                throw new IllegalArgumentException(e.getCause());
            }
        }
    } else {
        LOG.info(
                "Update for {} was attempted, although the "
                        + "connector only has these capabilities: {}. No action.",
                uid.getUidValue(), connInstance.getCapabilities());
    }

    return result;
}

From source file:org.openspaces.admin.internal.space.DefaultSpace.java

public void refreshScheduledSpaceMonitors() {
    for (Future fetcher : scheduledRuntimeFetchers.values()) {
        fetcher.cancel(false);
    }/*w  ww  .  j  a  v  a2  s. co  m*/
    for (SpaceInstance spaceInstance : this) {
        Future fetcher = admin.scheduleWithFixedDelay(new ScheduledRuntimeFetcher(spaceInstance),
                admin.getScheduledSpaceMonitorInterval(), admin.getScheduledSpaceMonitorInterval(),
                TimeUnit.MILLISECONDS);
        scheduledRuntimeFetchers.put(spaceInstance.getUid(), fetcher);
    }
}

From source file:dk.ange.octave.exec.OctaveExec.java

/**
 * @param input//from  ww w  .ja v  a2 s  .c  o m
 * @param output
 */
public void eval(final WriteFunctor input, final ReadFunctor output) {
    final String spacer = generateSpacer();
    final Future<Void> writerFuture = executor.submit(new OctaveWriterCallable(processWriter, input, spacer));
    final Future<Void> readerFuture = executor.submit(new OctaveReaderCallable(processReader, output, spacer));
    final RuntimeException writerException = getFromFuture(writerFuture);
    if (writerException instanceof CancellationException) {
        log.error("Did not expect writer to be canceled", writerException);
    }
    if (writerException != null) {
        if (writerException instanceof CancellationException) {
            log.error("Did not expect writer to be canceled", writerException);
        }
        readerFuture.cancel(true);
    }
    final RuntimeException readerException = getFromFuture(readerFuture);
    if (writerException != null) {
        throw writerException;
    }
    if (readerException != null) {
        // Only gets here when writerException==null, and in that case we don't expect the reader to be cancelled
        if (readerException instanceof CancellationException) {
            log.error("Did not expect reader to be canceled", writerException);
        }
        throw readerException;
    }
}

From source file:org.apache.omid.tso.TestBatchPool.java

@Test(timeOut = 10_000)
public void testBatchPoolBlocksWhenAllObjectsAreActive() throws Exception {

    ExecutorService executor = Executors.newCachedThreadPool();

    final ObjectPool<Batch> batchPool = injector.getInstance(Key.get(new TypeLiteral<ObjectPool<Batch>>() {
    }));/*from w  w w  . j  a  v  a2s  .co  m*/

    // Try to get one more batch than the number of concurrent writers set
    for (int i = 0; i < CONCURRENT_WRITERS + 1; i++) {

        // Wrap the call to batchPool.borrowObject() in a task to detect when is blocked by the ObjectPool
        Callable<Batch> task = new Callable<Batch>() {
            public Batch call() throws Exception {
                return batchPool.borrowObject();
            }
        };

        Future<Batch> future = executor.submit(task);

        try {
            /** The future below should return immediately except for the last one, which should be blocked by
            the ObjectPool as per the configuration setup in the {@link BatchPoolModule} */
            Batch batch = future.get(1, TimeUnit.SECONDS);
            LOG.info("Batch {} returned with success", batch.toString());
        } catch (TimeoutException ex) {
            if (i < CONCURRENT_WRITERS) {
                fail();
            } else {
                LOG.info("Yaaaayyyyy! This is the blocked call!");
            }
        } finally {
            future.cancel(true); // may or may not desire this
        }

    }

}

From source file:org.apache.syncope.core.provisioning.java.ConnectorFacadeProxy.java

@Override
public Uid authenticate(final String username, final String password, final OperationOptions options) {
    Uid result = null;//from  w w w. j a  v a2s .  com

    if (connInstance.getCapabilities().contains(ConnectorCapability.AUTHENTICATE)) {
        Future<Uid> future = asyncFacade.authenticate(connector, username,
                new GuardedString(password.toCharArray()), options);
        try {
            result = future.get(connInstance.getConnRequestTimeout(), TimeUnit.SECONDS);
        } catch (java.util.concurrent.TimeoutException e) {
            future.cancel(true);
            throw new TimeoutException("Request timeout");
        } catch (Exception e) {
            LOG.error("Connector request execution failure", e);
            if (e.getCause() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            } else {
                throw new IllegalArgumentException(e.getCause());
            }
        }
    } else {
        LOG.info(
                "Authenticate was attempted, although the connector only has these capabilities: {}. No action.",
                connInstance.getCapabilities());
    }

    return result;
}

From source file:org.apache.hadoop.hbase.backup.regionserver.LogRollBackupSubprocedurePool.java

/**
 * Wait for all of the currently outstanding tasks submitted via {@link #submitTask(Callable)}
 * @return <tt>true</tt> on success, <tt>false</tt> otherwise
 * @throws ForeignException exception//w ww  .j  a va2s .c o m
 */
public boolean waitForOutstandingTasks() throws ForeignException {
    LOG.debug("Waiting for backup procedure to finish.");

    try {
        for (Future<Void> f : futures) {
            f.get();
        }
        return true;
    } catch (InterruptedException e) {
        if (aborted) {
            throw new ForeignException("Interrupted and found to be aborted while waiting for tasks!", e);
        }
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        if (e.getCause() instanceof ForeignException) {
            throw (ForeignException) e.getCause();
        }
        throw new ForeignException(name, e.getCause());
    } finally {
        // close off remaining tasks
        for (Future<Void> f : futures) {
            if (!f.isDone()) {
                f.cancel(true);
            }
        }
    }
    return false;
}

From source file:org.openspaces.admin.internal.space.DefaultSpace.java

public InternalSpaceInstance removeInstance(String uid) {
    assertStateChangesPermitted();//  w  w  w.j  a va 2s.  c  om
    final InternalSpaceInstance spaceInstance = (InternalSpaceInstance) spaceInstancesByUID.remove(uid);
    if (spaceInstance != null) {
        admin.scheduleAdminOperation(new Runnable() {
            @Override
            public void run() {
                while (spaceInstance.isMonitoring()) {
                    spaceInstance.stopStatisticsMonitor();
                }
            }
        });

        getPartition(spaceInstance).removeSpaceInstance(uid);
        String fullSpaceName = JSpaceUtilities.createFullSpaceName(
                spaceInstance.getSpaceUrl().getContainerName(), spaceInstance.getSpaceUrl().getSpaceName());
        spaceInstancesByMemberName.remove(fullSpaceName);
        spaceInstanceRemovedEventManager.spaceInstanceRemoved(spaceInstance);
        ((InternalSpaceInstanceRemovedEventManager) spaces.getSpaceInstanceRemoved())
                .spaceInstanceRemoved(spaceInstance);
        Future fetcher = scheduledRuntimeFetchers.remove(uid);
        if (fetcher != null) {
            fetcher.cancel(true);
        }
    }
    return spaceInstance;
}

From source file:de.hopmann.msc.slave.service.PackageInstallationBean.java

public Future<InstallationContext> acquireInstallation(PackageResolved packageResolved,
        PackageInstallerHolder packageInstallerHolder) throws PackageNotFoundException {
    // TODO exception, close context to rollback on error

    final InstallationContext context = new InstallationContext();

    final Future<PackageInstallationEntity> installationFuture = acquireInstallation(packageResolved,
            packageInstallerHolder, context);

    return new Future<InstallationContext>() {

        @Override/*w  ww .  j a v a 2s .co m*/
        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean cancelled = installationFuture.cancel(mayInterruptIfRunning);
            try {
                // Close installation context to release resources
                context.close();
            } catch (Exception e) {
                log.log(Level.WARNING, "Could not close installation context", e);
            }
            return cancelled;
        }

        @Override
        public InstallationContext get() throws InterruptedException, ExecutionException {
            context.setInstallation(installationFuture.get());
            return context;
        }

        @Override
        public InstallationContext get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            context.setInstallation(installationFuture.get(timeout, unit));
            return context;
        }

        @Override
        public boolean isCancelled() {
            return installationFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return installationFuture.isDone();
        }
    };

}