Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:edu.umass.cs.gnsserver.activecode.ActiveCodeHandler.java

/**
 * Runs the active code. Returns a {@link ValuesMap}.
 *
 * @param code64 base64 encoded active code, as stored in the db
 * @param guid the guid/*  www.  j av  a2  s .c  o  m*/
 * @param field the field
 * @param action either 'read' or 'write'
 * @param valuesMap
 * @param activeCodeTTL the remaining active code TTL
 * @return a Valuesmap
 */
public ValuesMap runCode(String code64, String guid, String field, String action, ValuesMap valuesMap,
        int activeCodeTTL) {
    String code = new String(Base64.decodeBase64(code64));
    String values = valuesMap.toString();
    ValuesMap result = null;

    ActiveCodeParams acp = new ActiveCodeParams(guid, field, action, code, values, activeCodeTTL);
    FutureTask<ValuesMap> futureTask = new FutureTask<>(new ActiveCodeTask(acp, clientPool));

    // If the guid is blacklisted, just return immediately
    if (isBlacklisted(guid)) {
        System.out.println("Guid " + guid + " is blacklisted from running code!");
        return valuesMap;
    }

    // Only run if there are free workers and queue space
    // This prevents excessive CPU usage
    if (executorPool.getPoolSize() > 0 && executorPool.getQueue().remainingCapacity() > 0) {
        executorPool.execute(futureTask);

        try {
            result = futureTask.get();
        } catch (ExecutionException e) {
            System.out.println("Added " + guid + " to blacklist!");
            addToBlacklist(guid);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Rejecting task!");
    }

    return result;
}

From source file:de.uni_rostock.goodod.owl.OntologyCache.java

private synchronized FutureTask<OWLOntology> getOntologyFutureAtURI(final URI u)
        throws OWLOntologyCreationException {
    FutureTask<OWLOntology> future = null;

    future = futures.get(u);//w  w w  . ja v a 2s.c  om
    if (null != future) {
        return future;
    }
    future = new FutureTask<OWLOntology>(new Callable<OWLOntology>() {
        public OWLOntology call() throws ExecutionException {
            OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
            if (null != mappers) {
                for (OWLOntologyIRIMapper m : mappers) {
                    manager.addIRIMapper(m);
                }
            }
            FileDocumentSource source = new FileDocumentSource(new File(u));
            OWLOntology ontology;
            try {
                ontology = manager.loadOntologyFromOntologyDocument(source, config);
                markOriginalClasses(ontology);
                logger.info("Loading and normalizing ontology from " + u.toString() + ".");
                if (null != normalizerFactory) {
                    normalizerFactory.normalize(ontology);
                }
            } catch (OWLOntologyCreationException e) {
                throw new ExecutionException(e);
            }
            // Mark this future as done.
            futureDone();
            return ontology;
        }
    });
    futures.put(u, future);
    // We track our pending futures
    pendingFutures.incrementAndGet();
    executor.execute(future);

    return future;
}

From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java

@Test
public void testGetSameInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();
    final StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L);
    ExecutionContext executionContext = stepExecution.getExecutionContext();
    executionContext.put("foo", "foo");
    StepSynchronizationManager.register(stepExecution);
    assertEquals("foo", simple.getName());

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override/*from  ww  w  .  ja v  a2  s  .  com*/
            public String call() throws Exception {
                ExecutionContext executionContext = stepExecution.getExecutionContext();
                executionContext.put("foo", value);
                StepContext context = StepSynchronizationManager.register(stepExecution);
                logger.debug("Registered: " + context.getStepExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    StepSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    for (FutureTask<String> task : tasks) {
        assertEquals("foo", task.get());
    }

    // Don't close the outer scope until all tasks are finished. This should
    // always be the case if using an AbstractStep
    StepSynchronizationManager.close();

}

From source file:com.github.jknack.handlebars.cache.HighConcurrencyTemplateCache.java

/**
 * Creates a new future task for compiling the given source.
 *
 * @param source The template source./*  ww w  . ja va  2s.co m*/
 * @param parser The handlebars parser.
 * @return A new future task.
 */
private FutureTask<Pair<TemplateSource, Template>> newTask(final TemplateSource source, final Parser parser) {
    return new FutureTask<Pair<TemplateSource, Template>>(new Callable<Pair<TemplateSource, Template>>() {
        @Override
        public Pair<TemplateSource, Template> call() throws IOException {
            return Pair.of(source, parser.parse(source));
        }
    });
}

From source file:org.activiti.camel.CamelBehavior.java

public void execute(ActivityExecution execution) throws Exception {
    setAppropriateCamelContext(execution);

    final ActivitiEndpoint endpoint = createEndpoint(execution);
    final Exchange exchange = createExchange(execution, endpoint);

    if (isASync(execution)) {

        FutureTask<Void> future = new FutureTask<Void>(new Callable<Void>() {
            public Void call() {
                try {
                    endpoint.process(exchange);
                } catch (Exception e) {
                    throw new RuntimeException("Unable to process camel endpint asynchronously.");
                }//from   w  ww  . j a v a2s  .  co  m
                return null;
            }
        });
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(future);
        handleCamelException(exchange);

    } else {
        endpoint.process(exchange);
        handleCamelException(exchange);
        execution.setVariables(ExchangeUtils.prepareVariables(exchange, endpoint));
    }

    leave(execution);
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Checks the server if a username is available
 *
 * @param usernameToCheck The username that should be checked
 * @return <b>true</b> if the username exists already, <b>false</b> if not
 * @throws ExecutionException/* ww w  . j av  a  2s. c  o m*/
 * @throws InterruptedException
 */
public boolean checkUsernameAvailable(final String usernameToCheck)
        throws ExecutionException, InterruptedException {
    Callable<Boolean> booleanCallable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                String response = getMethod(
                        "http://www.balticapp.fi/lukeA/user/available?username=" + usernameToCheck);
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(response);
                    // TODO: 17/11/2016 make alert that username is taken
                    if (jsonObject.has("exists")) {
                        return !jsonObject.getBoolean("exists");
                    } else {
                        return false;
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "onPostExecute: ", e);
                    return false;
                }

            } catch (MalformedURLException e) {
                Log.e(TAG, "doInBackground: ", e);
                return false;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return false;
            }
        }
    };
    FutureTask<Boolean> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread thread = new Thread(booleanFutureTask);
    thread.start();
    return booleanFutureTask.get();

}

From source file:com.github.vatbub.tictactoe.view.AnimationThreadPoolExecutor.java

/**
 * @throws RejectedExecutionException {@inheritDoc}
 * @throws NullPointerException       {@inheritDoc}
 *///from   ww w  .j ava 2  s  .c  om
@NotNull
@Override
public <T> Future<T> submit(Callable<T> task) {
    Callable<T> effectiveTask = () -> {
        FutureTask<T> effectiveCall = new FutureTask<>(task);
        Platform.runLater(effectiveCall);
        return effectiveCall.get();
    };
    return super.schedule(effectiveTask, 0, NANOSECONDS);
}

From source file:org.atomserver.core.dbstore.DBBasedAtomCollection.java

protected <T> T executeTransactionally(final TransactionalTask<T> task) {
    final String t_user = AtomServerUserInfo.getUser();
    FutureTask<T> timeoutTask = null;
    try {//from w w  w .  j  a v a  2s. c om
        // create new timeout task
        timeoutTask = new FutureTask<T>(new Callable() {
            public T call() throws Exception {
                return (T) getTransactionTemplate().execute(new TransactionCallback() {
                    public Object doInTransaction(TransactionStatus transactionStatus) {
                        AtomServerUserInfo.setUser(t_user);
                        StopWatch stopWatch = new AtomServerStopWatch();
                        try {
                            // NOTE: we will actually wait for all of these to possibly finish,
                            //       unless the methods below honor InterruptedExceptions
                            //       BUT the transaction will still be rolled back eventually by the catch below.
                            getWriteEntriesDAO().acquireLock();
                            return task.execute();

                        } catch (Exception ee) {
                            if (ee instanceof EntryNotFoundException && (((EntryNotFoundException) ee)
                                    .getType() == EntryNotFoundException.EntryNotFoundType.DELETE)) {
                                log.warn("Exception in DB transaction", ee);
                            } else {
                                log.error("Exception in DB transaction", ee);
                            }

                            // the following is not really required, but ensures that this will rollback, without question
                            transactionStatus.setRollbackOnly();

                            if (ee instanceof InterruptedException) {
                                // InterruptedException - if the current thread was interrupted while waiting
                                // Re-assert the thread's interrupted status
                                Thread.currentThread().interrupt();
                            }
                            // NOTE: per the Spring manual, a transaction is ONLY rolled back
                            //       when a RuntimeException is thrown!!!
                            //       And the timeout causes an InterruptedException (via task.cancel()),
                            //       which is NOT Runtime!!
                            //       (AtomServerException extends RuntimeException)
                            throw (ee instanceof AtomServerException) ? (AtomServerException) ee
                                    : new AtomServerException("A " + ee.getCause().getClass().getSimpleName()
                                            + " caught in Transaction", ee.getCause());

                        } finally {
                            stopWatch.stop("DB.txn", "DB.txn");
                        }
                    }
                });
            }
        });
        // start timeout task in a new thread
        new Thread(timeoutTask).start();

        // wait for the execution to finish, timeout after X secs
        int timeout = (getTransactionTemplate().getTimeout() > 0) ? getTransactionTemplate().getTimeout()
                : DEFAULT_TXN_TIMEOUT;

        return timeoutTask.get(timeout, TimeUnit.SECONDS);

    } catch (AtomServerException ee) {
        log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage());
        throw ee;
    } catch (ExecutionException ee) {
        log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage());
        throw (ee.getCause() == null)
                ? new AtomServerException("A " + ee.getClass().getSimpleName() + " caught in Transaction", ee)
                : (ee.getCause() instanceof AtomServerException) ? (AtomServerException) ee.getCause()
                        : new AtomServerException(
                                "A " + ee.getCause().getClass().getSimpleName() + " caught in Transaction",
                                ee.getCause());
    } catch (Exception ee) {
        log.debug("Exception in DB TXN: " + ee.getClass().getSimpleName() + " " + ee.getMessage());
        throw new AtomServerException("A " + ee.getClass().getSimpleName() + " caught in Transaction", ee);
    } finally {
        // NOTE: We MUST call timeoutTask.cancel() here.
        //       This is the ONLY way that we see an InterruptedException in the transaction task,
        //       and thus, the ONLY way that we can make the transaction rollback.
        // NOTE: Calling cancel() on a completed task is a noop.
        log.debug("@@@@@@@@@@@@@@ Calling task.cancel");
        timeoutTask.cancel(true);
        timeoutTask = null;
    }
}

From source file:org.nuxeo.ecm.core.event.impl.PostCommitEventExecutor.java

public void run(List<EventListenerDescriptor> listeners, EventBundle bundle, long timeoutMillis, boolean bulk) {
    // check that there's at list one listener interested
    boolean some = false;
    for (EventListenerDescriptor listener : listeners) {
        if (listener.acceptBundle(bundle)) {
            some = true;//  w ww . jav  a2  s  . c  o  m
            break;
        }
    }
    if (!some) {
        if (log.isDebugEnabled()) {
            log.debug("Events postcommit execution has nothing to do");
        }
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Events postcommit execution starting with timeout %sms%s",
                Long.valueOf(timeoutMillis), bulk ? " in bulk mode" : ""));
    }

    Callable<Boolean> callable = !bulk ? new EventBundleRunner(listeners, bundle)
            : new EventBundleBulkRunner(listeners, bundle);
    FutureTask<Boolean> futureTask = new FutureTask<Boolean>(callable);
    try {
        executor.execute(futureTask);
    } catch (RejectedExecutionException e) {
        log.error("Events postcommit execution rejected", e);
        return;
    }
    try {
        // wait for runner to be finished, with timeout
        Boolean ok = futureTask.get(timeoutMillis, TimeUnit.MILLISECONDS);
        if (Boolean.FALSE.equals(ok)) {
            log.error("Events postcommit bulk execution aborted due to previous error");
        }
    } catch (InterruptedException e) {
        // restore interrupted status
        Thread.currentThread().interrupt();
        // interrupt thread
        futureTask.cancel(true); // mayInterruptIfRunning=true
    } catch (TimeoutException e) {
        if (!bulk) {
            log.warn(String.format(
                    "Events postcommit execution exceeded timeout of %sms, leaving thread running",
                    Long.valueOf(timeoutMillis)));
            // don't cancel task, let it run
        } else {
            log.error(String.format(
                    "Events postcommit bulk execution exceeded timeout of %sms, interrupting thread",
                    Long.valueOf(timeoutMillis)));
            futureTask.cancel(true); // mayInterruptIfRunning=true
        }
    } catch (ExecutionException e) {
        log.error("Events postcommit execution encountered unexpected exception", e.getCause());
    }

    if (log.isDebugEnabled()) {
        log.debug("Events postcommit execution finished");
    }
}

From source file:com.test.test.MultipleRequestsForServerTest.java

@Test
public void testSingleClientsForServer() throws Exception {
    // Number of threads
    final int size = 20;

    LOG.debug("clientSimple1:" + clientSimple);

    IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);

    List<ClientCallableForServer> clientCallableList = new ArrayList<ClientCallableForServer>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallableForServer(proxyService, i));
    }//from w w  w  .  ja v a 2  s  .c o  m

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallableForServer clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");

    Thread.sleep(20000);
    LOG.debug("\n\n\n\n+++++++++++++++++++++++++");
    LOG.debug("New system:");
    IServiceSimple proxyService2 = clientSimple.getProxy(IServiceSimple.class);
    proxyService2.functionNumber1("1", "1");

    LOG.debug("\n\n\n\n===========================");
    LOG.debug("And just sleep for empty pool");
    Thread.sleep(40000);
    IServiceSimple proxyService3 = clientSimple.getProxy(IServiceSimple.class);
    proxyService3.functionNumber1("1", "1");
}