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:com.alibaba.otter.node.etl.extract.extractor.DatabaseExtractor.java

private void cancel(List<Future> futures) {
    for (int i = 0; i < futures.size(); i++) {
        Future future = futures.get(i);
        if (future.isDone() == false) {
            future.cancel(true);// ??
        }//from w w  w .j ava  2  s .  co  m
    }
}

From source file:org.apache.http.HC4.impl.conn.PoolingHttpClientConnectionManager.java

@Override
public ConnectionRequest requestConnection(final HttpRoute route, final Object state) {
    Args.notNull(route, "HTTP route");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Connection request: " + format(route, state) + formatStats(route));
    }/*w w w.  j a va 2  s.com*/
    final Future<CPoolEntry> future = this.pool.lease(route, state, null);
    return new ConnectionRequest() {

        @Override
        public boolean cancel() {
            return future.cancel(true);
        }

        @Override
        public HttpClientConnection get(final long timeout, final TimeUnit tunit)
                throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            return leaseConnection(future, timeout, tunit);
        }

    };

}

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

@Override
public Set<ObjectClassInfo> getObjectClassInfo() {
    Future<Set<ObjectClassInfo>> future = asyncFacade.getObjectClassInfo(connector);
    try {//from www .  j a  v a 2  s  . co m
        return 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());
        }
    }
}

From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java

@Test
public void testRequestConnectionFutureCancelled() throws Exception {
    final HttpHost target = new HttpHost("localhost");
    final HttpRoute route = new HttpRoute(target);
    final Future<NHttpClientConnection> future = connman.requestConnection(route, "some state", 1000L, 2000L,
            TimeUnit.MILLISECONDS, null);
    Assert.assertNotNull(future);/*  ww w .  j a va 2  s  . c  o  m*/
    future.cancel(true);

    Mockito.verify(pool).lease(Matchers.same(route), Matchers.eq("some state"), Matchers.eq(1000L),
            Matchers.eq(2000L), Matchers.eq(TimeUnit.MILLISECONDS), poolEntryCallbackCaptor.capture());
    final FutureCallback<CPoolEntry> callaback = poolEntryCallbackCaptor.getValue();
    final Log log = Mockito.mock(Log.class);
    final CPoolEntry poolentry = new CPoolEntry(log, "some-id", route, conn, -1, TimeUnit.MILLISECONDS);
    poolentry.markRouteComplete();
    callaback.completed(poolentry);

    Mockito.verify(pool).release(poolentry, true);
}

From source file:org.jahia.services.SpringContextSingleton.java

private static Object getBeanInModulesContext(final String beanId, long waitTimeout) {

    for (JahiaTemplatesPackage aPackage : ServicesRegistry.getInstance().getJahiaTemplateManagerService()
            .getAvailableTemplatePackages()) {
        if (aPackage.getContext() != null && aPackage.getContext().containsBean(beanId)) {
            return aPackage.getContext().getBean(beanId);
        }/*from w ww .j a  va  2 s. c om*/
    }

    // Waiting for a missing bean only makes sense in case it is a part of application context initialization
    // during module startup, because there is a chance for the bean to appear later. Otherwise, multiple threads
    // waiting for missing beans could cause application collapse.
    if (waitTimeout > 0 && isApplicationContextInitializationInProgress()) {

        ExecutorService executor = Executors.newSingleThreadExecutor();

        Future<Object> future = executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                while (true) {
                    Thread.sleep(100);
                    try {
                        return getBeanInModulesContext(beanId, 0);
                    } catch (NoSuchBeanDefinitionException e) {
                        logger.debug("Bean '{}' not found by the task loop, will retry in 100 ms", beanId);
                    }
                }
            }
        });

        if (SettingsBean.getInstance().isDevelopmentMode()) {
            logger.warn(
                    "Detected call to SpringContextSingleton.getBeanInModulesContext(...) for bean '{}' during module startup."
                            + "Since 7.2.0.0 modules spring contexts are started independently, and beans may not be available."
                            + "We recommend to use OSGI services instead of spring beans to communicate between modules.",
                    beanId);
        }
        logger.info("Bean '{}' not found yet, will wait for its availability max {} seconds...", beanId,
                waitTimeout);

        try {
            return future.get(waitTimeout, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            future.cancel(true);
            logger.debug("Waiting for bean '{}' timed out", beanId);
        } catch (InterruptedException | ExecutionException e) {
            throw new JahiaRuntimeException(e);
        } finally {
            executor.shutdownNow();
        }

        logger.info("Bean '{}' not found in module contexts", beanId);
    }

    throw new NoSuchBeanDefinitionException(beanId);
}

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

@Override
public void delete(final ObjectClass objectClass, final Uid uid, final OperationOptions options,
        final Boolean[] propagationAttempted) {

    if (connInstance.getCapabilities().contains(ConnectorCapability.DELETE)) {
        propagationAttempted[0] = true;/* w w w.  j  a  v  a  2s  .  com*/

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

        try {
            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(
                "Delete for {} was attempted, although the connector only has these capabilities: {}. No action.",
                uid.getUidValue(), connInstance.getCapabilities());
    }
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

protected SyncLanClientQueryResult findSyncLanClient(SyncFile syncFile) throws Exception {

    SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncFile.getSyncAccountId());

    List<String> syncLanClientUuids = SyncLanEndpointService
            .findSyncLanClientUuids(syncAccount.getLanServerUuid(), syncFile.getRepositoryId());

    if (syncLanClientUuids.isEmpty()) {
        return null;
    }//  w  w  w.  j a v a  2s  .c o  m

    final List<Callable<SyncLanClientQueryResult>> syncLanClientQueryResultCallables = Collections
            .synchronizedList(new ArrayList<Callable<SyncLanClientQueryResult>>(syncLanClientUuids.size()));

    for (String syncLanClientUuid : syncLanClientUuids) {
        SyncLanClient syncLanClient = SyncLanClientService.fetchSyncLanClient(syncLanClientUuid);

        syncLanClientQueryResultCallables.add(createSyncLanClientQueryResultCallable(syncLanClient, syncFile));
    }

    int queryPoolSize = Math.min(syncLanClientUuids.size(), PropsValues.SYNC_LAN_SESSION_QUERY_POOL_MAX_SIZE);

    List<Future<SyncLanClientQueryResult>> pendingSyncLanClientQueryResults = new ArrayList<>(queryPoolSize);

    ExecutorCompletionService<SyncLanClientQueryResult> executorCompletionService = new ExecutorCompletionService<>(
            getExecutorService());

    for (int i = 0; i < queryPoolSize; i++) {
        Callable<SyncLanClientQueryResult> callable = new Callable<SyncLanClientQueryResult>() {

            @Override
            public synchronized SyncLanClientQueryResult call() throws Exception {

                if (syncLanClientQueryResultCallables.isEmpty()) {
                    return null;
                }

                Callable<SyncLanClientQueryResult> syncLanClientQueryResultCallable = syncLanClientQueryResultCallables
                        .remove(0);

                try {
                    return syncLanClientQueryResultCallable.call();
                } catch (Exception e) {
                    return call();
                }
            }

        };

        pendingSyncLanClientQueryResults.add(executorCompletionService.submit(callable));
    }

    List<Future<SyncLanClientQueryResult>> completedSyncLanClientQueryResult = new ArrayList<>(queryPoolSize);

    long timeout = PropsValues.SYNC_LAN_SESSION_QUERY_TOTAL_TIMEOUT;

    long endTime = System.currentTimeMillis() + timeout;

    for (int i = 0; i < queryPoolSize; i++) {
        Future<SyncLanClientQueryResult> future = executorCompletionService.poll(timeout,
                TimeUnit.MILLISECONDS);

        if (future == null) {
            for (Future<SyncLanClientQueryResult> pendingSyncLanClientQueryResult : pendingSyncLanClientQueryResults) {

                if (!pendingSyncLanClientQueryResult.isDone()) {
                    pendingSyncLanClientQueryResult.cancel(true);
                }
            }

            break;
        }

        completedSyncLanClientQueryResult.add(future);

        timeout = endTime - System.currentTimeMillis();
    }

    SyncLanClientQueryResult candidateSyncLanClientQueryResult = null;
    int candidateDownloadRatePerConnection = 0;

    for (Future<SyncLanClientQueryResult> completedFuture : completedSyncLanClientQueryResult) {

        SyncLanClientQueryResult syncLanClientQueryResult = null;

        try {
            syncLanClientQueryResult = completedFuture.get();
        } catch (Exception e) {
            continue;
        }

        if (syncLanClientQueryResult == null) {
            continue;
        }

        if (syncLanClientQueryResult.getConnectionsCount() >= syncLanClientQueryResult.getMaxConnections()) {

            if (candidateSyncLanClientQueryResult == null) {
                candidateSyncLanClientQueryResult = syncLanClientQueryResult;
            }

            continue;
        }

        if (syncLanClientQueryResult.getConnectionsCount() == 0) {
            return syncLanClientQueryResult;
        }

        int downloadRatePerConnection = syncLanClientQueryResult.getDownloadRate()
                / (syncLanClientQueryResult.getConnectionsCount() + 1);

        if (downloadRatePerConnection >= candidateDownloadRatePerConnection) {

            candidateDownloadRatePerConnection = downloadRatePerConnection;
            candidateSyncLanClientQueryResult = syncLanClientQueryResult;
        }
    }

    return candidateSyncLanClientQueryResult;
}

From source file:com.blacklocus.qs.worker.WorkerQueueItemHandler.java

@SuppressWarnings("unchecked")
@Override/*from  w ww  .  j  a  v  a  2s  .c o  m*/
public void withFuture(QSTaskModel task, final Future<Pair<QSTaskModel, Object>> future) {
    // I don't know if this is useful or not.

    QSWorker worker = workers.get(task.handler);
    if (worker == null) {
        throw new RuntimeException("No worker available for worker identifier: " + task.handler);
    }

    final TaskKitFactory factory = new TaskKitFactory(task, worker, logService, workerIdService);
    worker.withFuture(factory, new Future<Pair<TaskKitFactory, Object>>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

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

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

        @Override
        public Pair<TaskKitFactory, Object> get() throws InterruptedException, ExecutionException {
            Pair<QSTaskModel, Object> theFuture = future.get();
            return Pair.of(factory, theFuture.getRight());
        }

        @Override
        public Pair<TaskKitFactory, Object> get(long timeout,
                @SuppressWarnings("NullableProblems") TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            Pair<QSTaskModel, Object> theFuture = future.get(timeout, unit);
            return Pair.of(factory, theFuture.getRight());
        }
    });
}

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

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

    Uid result = null;/*from www .j a  v  a2 s  .  com*/

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

        Future<Uid> future = asyncFacade.create(connector, objectClass, 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("Create was attempted, although the connector only has these capabilities: {}. No action.",
                connInstance.getCapabilities());
    }

    return result;
}

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

@Override
public SyncToken getLatestSyncToken(final ObjectClass objectClass) {
    SyncToken result = null;// ww w  . j av a  2  s . co  m

    if (connInstance.getCapabilities().contains(ConnectorCapability.SYNC)) {
        Future<SyncToken> future = asyncFacade.getLatestSyncToken(connector, objectClass);

        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(
                "getLatestSyncToken was attempted, although the "
                        + "connector only has these capabilities: {}. No action.",
                connInstance.getCapabilities());
    }

    return result;
}