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:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java

/**
 * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle.
 *
 * @param script the script to evaluate//  w w w. j av a  2s .  c om
 * @param language the language to evaluate it in
 * @param boundVars the bindings to evaluate in the context of the script
 * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process
 */
public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars,
        final LifeCycle lifeCycle) {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    logger.debug("Preparing to evaluate script - {} - in thread [{}]", script,
            Thread.currentThread().getName());

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(globalBindings);
    bindings.putAll(boundVars);

    final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>();
    final FutureTask<Void> f = new FutureTask<>(() -> {
        try {
            lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings);

            logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName());

            final Object o = scriptEngines.eval(script, bindings, lang);

            // apply a transformation before sending back the result - useful when trying to force serialization
            // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some
            // transactional constraints
            final Object result = lifeCycle.getTransformResult().isPresent()
                    ? lifeCycle.getTransformResult().get().apply(o)
                    : o;

            // a mechanism for taking the final result and doing something with it in the same thread, but
            // AFTER the eval and transform are done and that future completed.  this provides a final means
            // for working with the result in the same thread as it was eval'd
            if (lifeCycle.getWithResult().isPresent())
                lifeCycle.getWithResult().get().accept(result);

            lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings);

            // the evaluationFuture must be completed after all processing as an exception in lifecycle events
            // that must raise as an exception to the caller who has the returned evaluationFuture. in other words,
            // if it occurs before this point, then the handle() method won't be called again if there is an
            // exception that ends up below trying to completeExceptionally()
            evaluationFuture.complete(result);
        } catch (Throwable ex) {
            final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex);

            // thread interruptions will typically come as the result of a timeout, so in those cases,
            // check for that situation and convert to TimeoutException
            if (root instanceof InterruptedException)
                evaluationFuture.completeExceptionally(new TimeoutException(String.format(
                        "Script evaluation exceeded the configured 'scriptEvaluationTimeout' threshold of %s ms for request [%s]: %s",
                        scriptEvaluationTimeout, script, root.getMessage())));
            else {
                lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root);
                evaluationFuture.completeExceptionally(root);
            }
        }

        return null;
    });

    executorService.execute(f);

    if (scriptEvaluationTimeout > 0) {
        // Schedule a timeout in the thread pool for future execution
        final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> {
            logger.warn("Timing out script - {} - in thread [{}]", script, Thread.currentThread().getName());
            if (!f.isDone()) {
                lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings);
                f.cancel(true);
            }
        }, scriptEvaluationTimeout, TimeUnit.MILLISECONDS);

        // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed
        // with exception
        evaluationFuture.handleAsync((v, t) -> {
            logger.debug(
                    "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception).");
            return sf.cancel(true);
        });
    }

    return evaluationFuture;
}

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

/**
 * Report an inappropriate submissions by id
 *
 * @param submissionId The ID of the given submission.
 * @return <b>true</b> if the request passes, <b>false</b> if it doesn't.
 *///from  w w  w .  j  a  v  a2  s . c  om
public String reportSubmission(final String submissionId) {
    Callable<String> booleanCallable = new Callable<String>() {
        @Override
        public String call() throws Exception {
            String jsonString = getMethod("http://www.balticapp.fi/lukeA/report/flag?id=" + submissionId);
            Log.e(TAG, "updateUserImage run: Result : " + jsonString);
            return "Error reporting";

        }
    };
    FutureTask<String> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread t = new Thread(booleanFutureTask);
    t.start();
    try {
        return booleanFutureTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e(TAG, "reportSubmission: ", e);
        return null;
    }

}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

public void updateTree(List<TreeNode> add, List<TreeNode> remove) {
    Set<TreeItem<TreeNode>> updated = new HashSet<>();

    ArrayDeque<TreeNode> queue = new ArrayDeque<>();
    queue.addAll(add);/*w  w w .jav  a  2  s.  c  o  m*/

    while (!queue.isEmpty()) {
        TreeNode thisNode = queue.pop();

        TreeItem<TreeNode> parent;

        if (thisNode.getParent() == null) {
            parent = rootItem;
        } else {
            parent = itemMap.get(thisNode.getParent());
        }

        updated.add(parent);

        TreeItem<TreeNode> thisItem = new TreeItem<>(thisNode);
        thisItem.addEventHandler(TreeItem.<TreeNode>branchExpandedEvent(), event -> {
            if (thisItem.getChildren().size() == 1) {
                thisItem.getChildren().get(0).setExpanded(true);
            }
        });
        thisItem.setGraphic(new ImageView(new Image(getIconForTreeItem(thisNode))));
        FutureTask<Void> call = new FutureTask<>(() -> {
            parent.getChildren().add(thisItem);
            return null;
        });
        Platform.runLater(call);
        try {
            call.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        itemMap.put(thisNode, thisItem);

        queue.addAll(thisNode.getChildren());
    }

    for (TreeItem<TreeNode> parent : updated) {
        if (parent.getChildren().size() > 1) {
            FutureTask<Void> call = new FutureTask<>(() -> {
                parent.getChildren().sort((a, b) -> {
                    int ac = a.getValue().getChildren().size();
                    int bc = b.getValue().getChildren().size();

                    if (ac == 0 && bc != 0)
                        return 1;
                    else if (ac != 0 && bc == 0)
                        return -1;
                    return a.getValue().getDisplayName().compareTo(b.getValue().getDisplayName());
                });
                return null;
            });
            Platform.runLater(call);
            try {
                call.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    queue.addAll(remove);

    while (!queue.isEmpty()) {
        TreeNode thisNode = queue.pop();
        TreeItem<TreeNode> thisItem = itemMap.remove(thisNode);
        thisItem.getParent().getChildren().remove(thisItem);
        queue.addAll(thisNode.getChildren());
    }
}

From source file:org.apache.hive.service.cli.CLIServiceTest.java

@Test
public void testExecuteStatementParallel() throws Exception {
    Map<String, String> confOverlay = new HashMap<String, String>();
    String tableName = "TEST_EXEC_PARALLEL";
    String columnDefinitions = "(ID STRING)";

    // Open a session and set up the test data
    SessionHandle sessionHandle = setupTestData(tableName, columnDefinitions, confOverlay);
    assertNotNull(sessionHandle);//from  w  w w.  j a  v a2  s. co m

    long longPollingTimeout = HiveConf.getTimeVar(new HiveConf(),
            HiveConf.ConfVars.HIVE_SERVER2_LONG_POLLING_TIMEOUT, TimeUnit.MILLISECONDS);
    confOverlay.put(HiveConf.ConfVars.HIVE_SERVER2_LONG_POLLING_TIMEOUT.varname, longPollingTimeout + "ms");

    int THREAD_COUNT = 10, QUERY_COUNT = 10;
    // TODO: refactor this into an utility, LLAP tests use this pattern a lot
    ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
    CountDownLatch cdlIn = new CountDownLatch(THREAD_COUNT), cdlOut = new CountDownLatch(1);
    @SuppressWarnings("unchecked")
    Callable<Void>[] cs = (Callable<Void>[]) new Callable[3];
    // Create callables with different queries.
    String query = "SELECT ID + %1$d FROM " + tableName;
    cs[0] = createQueryCallable(query, confOverlay, longPollingTimeout, QUERY_COUNT, cdlIn, cdlOut);
    query = "SELECT t1.ID, SUM(t2.ID) + %1$d FROM  " + tableName + " t1 CROSS JOIN " + tableName
            + " t2 GROUP BY t1.ID HAVING t1.ID > 1";
    cs[1] = createQueryCallable(query, confOverlay, longPollingTimeout, QUERY_COUNT, cdlIn, cdlOut);
    query = "SELECT b.a FROM (SELECT (t1.ID + %1$d) as a , t2.* FROM  " + tableName + " t1 INNER JOIN "
            + tableName + " t2 ON t1.ID = t2.ID WHERE t2.ID > 2) b";
    cs[2] = createQueryCallable(query, confOverlay, longPollingTimeout, QUERY_COUNT, cdlIn, cdlOut);

    @SuppressWarnings("unchecked")
    FutureTask<Void>[] tasks = (FutureTask<Void>[]) new FutureTask[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i) {
        tasks[i] = new FutureTask<Void>(cs[i % cs.length]);
        executor.execute(tasks[i]);
    }
    try {
        cdlIn.await(); // Wait for all threads to be ready.
        cdlOut.countDown(); // Release them at the same time.
        for (int i = 0; i < THREAD_COUNT; ++i) {
            tasks[i].get();
        }
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }

    // Cleanup
    client.executeStatement(sessionHandle, "DROP TABLE " + tableName, confOverlay);
    client.closeSession(sessionHandle);
}

From source file:org.wso2.carbon.caching.impl.CacheImpl.java

@Override
public Future<V> load(K key) {
    Util.checkAccess(ownerTenantDomain, ownerTenantId);
    checkStatusStarted();//from ww w . j a  v a  2  s.c o  m
    lastAccessed = System.currentTimeMillis();
    CacheLoader<K, ? extends V> cacheLoader = cacheConfiguration.getCacheLoader();
    if (cacheLoader == null) {
        return null;
    }
    if (containsKey(key)) {
        return null;
    }
    CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
    FutureTask<V> task = new FutureTask<V>(new CacheLoaderLoadCallable<K, V>(this, cacheLoader, key,
            carbonContext.getTenantDomain(), carbonContext.getTenantId()));
    cacheLoadExecService.submit(task);
    return task;
}

From source file:io.teak.sdk.TeakNotification.java

/**
 * Schedules a push notification for some time in the future.
 *
 * @param creativeId     The identifier of the notification in the Teak dashboard (will create if not found).
 * @param defaultMessage The default message to send, may be over-ridden in the dashboard.
 * @param delayInSeconds The delay in seconds from now to send the notification.
 * @return The identifier of the scheduled notification (see {@link TeakNotification#cancelNotification(String)} or null.
 *///  www .  j a va  2  s  . com
@SuppressWarnings("unused")
public static FutureTask<String> scheduleNotification(final String creativeId, final String defaultMessage,
        final long delayInSeconds) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring scheduleNotification().");
        return null;
    }

    if (creativeId == null || creativeId.isEmpty()) {
        Log.e(LOG_TAG, "creativeId cannot be null or empty");
        return null;
    }

    if (defaultMessage == null || defaultMessage.isEmpty()) {
        Log.e(LOG_TAG, "defaultMessage cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("identifier", creativeId);
            payload.put("message", defaultMessage);
            payload.put("offset", delayInSeconds);

            new Request("/me/local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }

                    ret.run();
                }
            }.run();
        }
    });
    return ret;
}

From source file:com.karura.framework.PluginManager.java

/**
 * Helper method to schedule a Callable on the background
 * //from   w  w  w .ja v  a 2  s  .  c o m
 * @param callable
 *            The task to be scheduled on the background thread
 * @param callback
 *            Reference to the callback object which needs to be notified when the callback has been executed successfully or otherwise.
 * @return Future Task for the Callable which was submitted to background executor
 */
@SuppressWarnings("unchecked")
public <T> Future<T> runInBackground(Callable<T> callable, final TaskCallback<T> callback) {
    FutureTask<T> ft = new FutureTask<T>(callable) {

        @Override
        protected void done() {
            if (callback == null)
                return;

            try {
                if (!isCancelled()) {
                    callback.done(get());
                }
            } catch (Exception e) {
                callback.error(e);
            }
        }

    };
    return (Future<T>) DEFAULT_EXECUTOR.submit(ft);
}

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

/**
 * Fetches all submissions by a user from the server.
 *
 * @param userID The ID of the user whose submissions should be fetched.
 * @return Returns an ArrayList of {@link Submission} objects.
 *//*from  w  w w . j  av  a2 s. com*/
public ArrayList<Submission> getSubmissionsByUser(final String userID) {
    Callable<ArrayList<Submission>> booleanCallable = new Callable<ArrayList<Submission>>() {
        @Override
        public ArrayList<Submission> call() throws Exception {
            String jsonString = getMethod("http://www.balticapp.fi/lukeA/report?submitterId=" + userID);
            if (!TextUtils.isEmpty(jsonString)) {
                JSONArray jsonArray = new JSONArray(jsonString);
                Log.e(TAG, "call: jsonArray" + jsonArray.toString());
                return LukeUtils.parseSubmissionsFromJsonArray(jsonArray);
            } else {
                return null;
            }

        }
    };

    FutureTask<ArrayList<Submission>> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread t = new Thread(booleanFutureTask);
    t.start();
    try {
        return booleanFutureTask.get();
    } catch (InterruptedException e) {
        Log.e(TAG, "reportSubmission: ", e);
        return null;
    } catch (ExecutionException e) {
        Log.e(TAG, "reportSubmission: ", e);
        return null;
    }
}

From source file:com.indeed.lsmtree.recordcache.PersistentRecordCache.java

/**
 * Performs lookup for multiple keys and returns a streaming iterator to results.
 * Each element in the iterator is one of
 *  (1) an exception associated with a single lookup
 *  (2) a key value tuple/*w  ww . jav a2s.  c  om*/
 *
 * @param keys      lookup keys
 * @param progress  (optional) an AtomicInteger for tracking progress
 * @param skipped   (optional) an AtomicInteger for tracking missing keys
 * @return          iterator of lookup results
 */
public Iterator<Either<Exception, P2<K, V>>> getStreaming(final @Nonnull Iterator<K> keys,
        final @Nullable AtomicInteger progress, final @Nullable AtomicInteger skipped) {
    log.info("starting store lookups");
    LongArrayList addressList = new LongArrayList();
    int notFound = 0;
    while (keys.hasNext()) {
        final K key = keys.next();
        final Long address;
        try {
            address = index.get(key);
        } catch (IOException e) {
            log.error("error", e);
            return Iterators.singletonIterator(Left.<Exception, P2<K, V>>of(new IndexReadException(e)));
        }
        if (address != null) {
            addressList.add(address);
        } else {
            notFound++;
        }
    }
    if (progress != null)
        progress.addAndGet(notFound);
    if (skipped != null)
        skipped.addAndGet(notFound);
    log.info("store lookups complete, sorting addresses");

    final long[] addresses = addressList.elements();
    Arrays.sort(addresses, 0, addressList.size());

    log.info("initializing store lookup iterator");
    final BlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(100);
    final Iterator<List<Long>> iterable = Iterators.partition(addressList.iterator(), 1000);
    final ExecutorService primerThreads = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, taskQueue,
            new NamedThreadFactory("store priming thread", true, log), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    try {
                        taskQueue.put(r);
                    } catch (InterruptedException e) {
                        log.error("error", e);
                        throw new RuntimeException(e);
                    }
                }
            });
    final BlockingQueue<List<Either<Exception, P2<K, V>>>> completionQueue = new ArrayBlockingQueue<List<Either<Exception, P2<K, V>>>>(
            10);
    final AtomicLong runningTasks = new AtomicLong(0);
    final AtomicBoolean taskSubmitterRunning = new AtomicBoolean(true);

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (iterable.hasNext()) {
                runningTasks.incrementAndGet();
                final List<Long> addressesSublist = iterable.next();
                primerThreads.submit(new FutureTask<List<Either<Exception, P2<K, V>>>>(
                        new RecordLookupTask(addressesSublist)) {
                    @Override
                    protected void done() {
                        try {
                            final List<Either<Exception, P2<K, V>>> results = get();
                            if (progress != null) {
                                progress.addAndGet(results.size());
                            }
                            completionQueue.put(results);
                        } catch (InterruptedException e) {
                            log.error("error", e);
                            throw new RuntimeException(e);
                        } catch (ExecutionException e) {
                            log.error("error", e);
                            throw new RuntimeException(e);
                        }
                    }
                });
            }
            taskSubmitterRunning.set(false);
        }
    }, "RecordLookupTaskSubmitterThread").start();

    return new Iterator<Either<Exception, P2<K, V>>>() {

        Iterator<Either<Exception, P2<K, V>>> currentIterator;

        @Override
        public boolean hasNext() {
            if (currentIterator != null && currentIterator.hasNext())
                return true;
            while (taskSubmitterRunning.get() || runningTasks.get() > 0) {
                try {
                    final List<Either<Exception, P2<K, V>>> list = completionQueue.poll(1, TimeUnit.SECONDS);
                    if (list != null) {
                        log.debug("remaining: " + runningTasks.decrementAndGet());
                        currentIterator = list.iterator();
                        if (currentIterator.hasNext())
                            return true;
                    }
                } catch (InterruptedException e) {
                    log.error("error", e);
                    throw new RuntimeException(e);
                }
            }
            primerThreads.shutdown();
            return false;
        }

        @Override
        public Either<Exception, P2<K, V>> next() {
            return currentIterator.next();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.normandra.cassandra.CassandraDatabaseSession.java

protected Future<ResultSet> executeAsync(final Statement statement) {
    final CassandraDatabaseActivity activity = new CassandraDatabaseActivity(statement, this.session);
    final Callable<ResultSet> callable = () -> activity.execute();
    final FutureTask<ResultSet> task = new FutureTask<>(callable);
    this.executor.execute(task);
    return task;//from w w  w.j a  v  a  2 s .  c  om
}