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:ubic.gemma.apps.Blat.java

/**
 * @param querySequenceFile//from   w  w w .  j a  va 2 s .c  o m
 * @param outputPath
 * @return processed results.
 */
private Collection<BlatResult> jniGfClientCall(final File querySequenceFile, final String outputPath,
        final int portToUse) throws IOException {
    try {
        log.debug("Starting blat run");

        FutureTask<Boolean> blatThread = new FutureTask<Boolean>(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                GfClientCall(host, Integer.toString(portToUse), seqDir, querySequenceFile.getPath(),
                        outputPath);
                return true;
            }
        });

        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(blatThread);
        executor.shutdown();

        // wait...
        StopWatch overallWatch = new StopWatch();
        overallWatch.start();

        while (!blatThread.isDone()) {
            try {
                Thread.sleep(BLAT_UPDATE_INTERVAL_MS);
            } catch (InterruptedException ie) {
                throw new RuntimeException(ie);
            }

            synchronized (outputPath) {
                File outputFile = new File(outputPath);
                Long size = outputFile.length();
                NumberFormat nf = new DecimalFormat();
                nf.setMaximumFractionDigits(2);
                String minutes = TimeUtil.getMinutesElapsed(overallWatch);
                log.info("BLAT output so far: " + nf.format(size / 1024.0) + " kb (" + minutes
                        + " minutes elapsed)");
            }

        }

        overallWatch.stop();
        String minutes = TimeUtil.getMinutesElapsed(overallWatch);
        log.info("Blat took a total of " + minutes + " minutes");

    } catch (UnsatisfiedLinkError e) {
        log.error(e, e);
        log.info("Falling back on exec()");
        this.execGfClient(querySequenceFile, outputPath, portToUse);
    }
    return this.processPsl(outputPath, null);
}

From source file:net.pms.io.ThreadedProcessWrapper.java

/**
 * Runs a process with the given command {@link List}.
 *
 * @param command an array of {@link String} used to build the command line.
 * @param timeoutMS the process timeout in milliseconds after which the
 *            process is terminated. Use zero for no timeout, but be aware
 *            of the <a href=/*ww w . ja  va 2s  .co m*/
 *            "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9"
 *            >pitfalls</a>
 * @param terminateTimeoutMS the timeout in milliseconds to wait for each
 *            termination attempt.
 * @return The {@link ProcessWrapperResult} from running the process.
 * @throws IllegalArgumentException If {@code command} is {@code null} or
 *             empty.
 */
@Nonnull
public Future<R> runProcess(@Nonnull final List<String> command, final long timeoutMS,
        final long terminateTimeoutMS) {
    if (command == null || command.isEmpty()) {
        throw new IllegalArgumentException("command can't be null or empty");
    }
    final String executableName;
    if (isNotBlank(command.get(0))) {
        Path executable = Paths.get(command.get(0)).getFileName();
        if (executable != null) {
            executableName = executable.toString();
        } else {
            executableName = command.get(0);
        }
    } else {
        executableName = command.get(0);
    }
    final int threadId = PROCESS_COUNTER.getAndIncrement();

    Callable<R> callable = new Callable<R>() {

        @Override
        public R call() throws InterruptedException {
            boolean manageProcess = timeoutMS > 0;
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            if (LOGGER.isTraceEnabled()) {
                //XXX: Replace with String.join() in Java 8
                LOGGER.trace("Executing \"{}\"", StringUtils.join(command, " "));
            }
            Process process;
            try {
                process = processBuilder.start();
            } catch (IOException e) {
                LOGGER.debug("IOException when trying to start \"{}\" process: {}", executableName,
                        e.getMessage());
                LOGGER.trace("", e);
                return consumer.createResult(null, Integer.MIN_VALUE, e);
            }
            Future<T> output = consumer.consume(process.getInputStream(),
                    "TPW \"" + executableName + "\" consumer " + threadId);
            if (manageProcess) {
                Services.processManager().addProcess(process, executableName, timeoutMS, terminateTimeoutMS);
            }
            int exitCode = Integer.MIN_VALUE;
            boolean interrupted = false;
            boolean shutdown = false;
            do {
                interrupted = false;
                try {
                    exitCode = process.waitFor();
                } catch (InterruptedException e) {
                    interrupted = Thread.interrupted();
                    if (!shutdown) {
                        if (manageProcess) {
                            Services.processManager().shutdownProcess(process, executableName);
                            manageProcess = false;
                        } else {
                            Services.processManager().addProcess(process, executableName, 0,
                                    terminateTimeoutMS);
                        }
                        shutdown = true;
                    }
                }
            } while (interrupted);
            if (manageProcess) {
                Services.processManager().removeProcess(process, executableName);
            }
            try {
                return consumer.createResult(output.get(), exitCode, null);
            } catch (ExecutionException e) {
                Throwable cause = e.getCause() != null ? e.getCause() : e;
                LOGGER.error("ExecutionException in \"{}\" consumer, no output will be returned: {}",
                        executableName, cause.getMessage());
                LOGGER.trace("", e);
                return consumer.createResult(null, exitCode, cause);
            }
        }
    };
    FutureTask<R> result = new FutureTask<R>(callable);
    Thread runner = new Thread(result, "TPW \"" + executableName + "\" " + threadId);
    runner.start();
    return result;
}

From source file:org.jactr.core.runtime.controller.OldController.java

public Future<Boolean> terminate() {
    if (LOGGER.isWarnEnabled())
        LOGGER.warn("NO OP");
    FutureTask<Boolean> rtn = new FutureTask<Boolean>(new Callable<Boolean>() {

        public Boolean call() throws Exception {
            try {

                return true;
            } catch (Exception e) {
                LOGGER.error("Failed to terminate runtime correctly ", e);
                return false;
            }//ww w .  j a  va  2  s. com
        }
    });

    rtn.run();
    return rtn;
}

From source file:com.revo.deployr.client.core.impl.RClientImpl.java

public RCoreResponse execute(RCall call) {

    AbstractCall abstractCall = (AbstractCall) call;
    abstractCall.addHeader(XSRF_HEADER, csrf);

    // Provide httpClient and DeployR server url context to RCall.
    abstractCall.setClient(httpClient, serverurl);
    Callable callable = (Callable) call;
    // Wrap Callable in FutureTask for execution by the Executor Service.
    FutureTask task = new FutureTask(callable);
    abstractCall.setFuture(task);/*  www  .ja va2s  .  c  o  m*/
    eService.submit(task);

    return (RCoreResponse) call;
}

From source file:org.geek.utils.ApplicationUtils.java

public static String getRequest(final String url) throws InterruptedException, ExecutionException {
    FutureTask<String> task = new FutureTask<String>(new Callable<String>() {

        @Override/*  w w  w .  ja va 2  s  .com*/
        public String call() throws Exception {
            // HttpGet  
            HttpGet get = new HttpGet(url);
            // ??get  
            HttpResponse httpResponse = httpClient.execute(get);
            // ???  
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // ???  
                return EntityUtils.toString(httpResponse.getEntity());
            }
            return null;
        }
    });
    new Thread(task).start();
    return task.get();
}

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

/**
 * Fewtches all users from the backend./*from   ww  w. j  ava2  s .  c o m*/
 * @return Arraylist of User objects
 * @throws ExecutionException
 * @throws InterruptedException
 */
public ArrayList<UserFromServer> getAllUsers() throws ExecutionException, InterruptedException {

    Callable<ArrayList<UserFromServer>> userFromServerCallable = new Callable<ArrayList<UserFromServer>>() {
        @Override
        public ArrayList<UserFromServer> call() throws Exception {
            String jsonString = getMethod("http://www.balticapp.fi/lukeA/user/get-all");
            Log.e(TAG, "doInBackground: STRING IS " + jsonString);
            if (!TextUtils.isEmpty(jsonString)) {
                ArrayList<UserFromServer> returnjeeben = new ArrayList<>();
                JSONArray jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    returnjeeben.add(LukeUtils.parseUserFromJsonObject(jsonArray.getJSONObject(i)));
                }
                return returnjeeben;
            } else {
                return null;
            }
        }
    };
    FutureTask<ArrayList<UserFromServer>> userFromServerFutureTask = new FutureTask<>(userFromServerCallable);
    Thread t = new Thread(userFromServerFutureTask);
    t.start();
    return userFromServerFutureTask.get();

}

From source file:com.sm.store.client.ClusterClient.java

/**
 *
 * @param invoker//from   w w w. j a va2s  .  c om
 * @param keys
 * @return future
 */
public Future clusterStoreProcFuture(final Invoker invoker, final List<Key> keys) {
    AtomicReference<FutureTask<List<Object>>> future = new AtomicReference<FutureTask<List<Object>>>(
            new FutureTask<List<Object>>(new Callable<List<Object>>() {
                public List<Object> call() {
                    return clusterStoreProc(invoker, keys);
                }
            }));
    futureExecutor.execute(future.get());
    return future.get();
}

From source file:org.apache.jackrabbit.oak.segment.CompactionAndCleanupIT.java

private static <T> FutureTask<T> runAsync(Callable<T> callable) {
    FutureTask<T> task = new FutureTask<T>(callable);
    new Thread(task).start();
    return task;//from  www. ja  va  2s  .c  om
}

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

/**
 * Fetches all ranks from the backend/* w w w .j  a va  2 s . c o  m*/
 * @return Arraylist of Rank objects
 * @throws ExecutionException
 * @throws InterruptedException
 */
public ArrayList<Rank> getAllRanks() throws ExecutionException, InterruptedException {
    Callable<ArrayList<Rank>> arrayListCallable = new Callable<ArrayList<Rank>>() {
        @Override
        public ArrayList<Rank> call() throws Exception {
            String allRanks = getMethod("http://www.balticapp.fi/lukeA/rank");
            JSONArray allRanksJson = new JSONArray(allRanks);
            ArrayList<Rank> ranks = LukeUtils.parseRanksFromJsonArray(allRanksJson);
            return ranks;
        }
    };
    FutureTask<ArrayList<Rank>> arrayListFutureTask = new FutureTask<ArrayList<Rank>>(arrayListCallable);
    Thread t = new Thread(arrayListFutureTask);
    t.start();
    return arrayListFutureTask.get();
}

From source file:org.kontalk.view.View.java

static <T> Optional<T> invokeAndWait(Callable<T> callable) {
    try {//from   w ww  .  ja  v a2s  .  co  m
        FutureTask<T> task = new FutureTask<>(callable);
        SwingUtilities.invokeLater(task);
        // blocking
        return Optional.of(task.get());
    } catch (ExecutionException | InterruptedException ex) {
        LOGGER.log(Level.WARNING, "can't execute task", ex);
    }
    return Optional.empty();
}