Example usage for java.util.concurrent FutureTask isDone

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

Introduction

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

Prototype

public boolean isDone() 

Source Link

Usage

From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java

public String loadCommitMessage(final String url) {
    final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() {
        public String call() {
            final HttpClient client = new HttpClient();
            final GetMethod getMethod = new GetMethod(url);
            try {
                final int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK)
                    throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")");
                return getMethod.getResponseBodyAsString();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }/*from   w w  w  .j  av a2  s.  com*/
        }
    });

    ApplicationManager.getApplication().executeOnPooledThread(downloadTask);

    try {
        return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        // ignore
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (!downloadTask.isDone()) {
        downloadTask.cancel(true);
        throw new RuntimeException("Connection timed out");
    }

    return "";
}

From source file:ubic.gemma.core.apps.ShellDelegatingBlat.java

/**
 * @param querySequenceFile query sequence file
 * @param outputPath        output path/*  ww w .ja va  2 s. c o m*/
 * @return processed results.
 */
private Collection<BlatResult> jniGfClientCall(final File querySequenceFile, final String outputPath,
        final int portToUse) throws IOException {
    try {
        ShellDelegatingBlat.log.debug("Starting blat run");

        FutureTask<Boolean> blatThread = new FutureTask<>(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                ShellDelegatingBlat.this.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(ShellDelegatingBlat.BLAT_UPDATE_INTERVAL_MS);
            } catch (InterruptedException ie) {
                throw new RuntimeException(ie);
            }
            this.outputFile(outputPath, overallWatch);
        }

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

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

From source file:ubic.gemma.apps.Blat.java

/**
 * @param querySequenceFile//  ww w  .j a  v  a  2s  .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:ubic.gemma.core.loader.util.fetcher.FtpArchiveFetcher.java

protected void unPack(final File toUnpack) {
    FutureTask<Boolean> future = new FutureTask<>(new Callable<Boolean>() {
        @Override//from ww w .  j  av  a  2s.c o  m
        @SuppressWarnings("synthetic-access")
        public Boolean call() {
            File extractedFile = new File(FileTools.chompExtension(toUnpack.getAbsolutePath()));
            /*
             * Decide if an existing file is plausibly usable. Err on the side of caution.
             */
            if (allowUseExisting && extractedFile.canRead() && extractedFile.length() >= toUnpack.length()
                    && !FileUtils.isFileNewer(toUnpack, extractedFile)) {
                AbstractFetcher.log.warn("Expanded file exists, skipping re-expansion: " + extractedFile);
                return Boolean.TRUE;
            }

            if (expander != null) {
                expander.setSrc(toUnpack);
                expander.setDest(toUnpack.getParentFile());
                expander.perform();
            } else if (toUnpack.getAbsolutePath().toLowerCase().endsWith("zip")) {
                try {
                    FileTools.unZipFiles(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            } else { // gzip.
                try {
                    FileTools.unGzipFile(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return Boolean.TRUE;
        }

    });
    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(future);
    executor.shutdown();

    StopWatch s = new StopWatch();
    s.start();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            future.cancel(true);
            return;
        }
        AbstractFetcher.log
                .info("Unpacking archive ... " + Math.floor(s.getTime() / 1000.0) + " seconds elapsed");
    }
}

From source file:ubic.gemma.loader.util.fetcher.FtpArchiveFetcher.java

/**
 * @param newDir/*  ww  w .jav  a 2  s .co m*/
 * @param seekFile
 */
protected void unPack(final File toUnpack) {
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        @SuppressWarnings("synthetic-access")
        public Boolean call() {
            File extractedFile = new File(FileTools.chompExtension(toUnpack.getAbsolutePath()));
            /*
             * Decide if an existing file is plausibly usable. Err on the side of caution.
             */
            if (allowUseExisting && extractedFile.canRead() && extractedFile.length() >= toUnpack.length()
                    && !FileUtils.isFileNewer(toUnpack, extractedFile)) {
                log.warn("Expanded file exists, skipping re-expansion: " + extractedFile);
                return Boolean.TRUE;
            }

            if (expander != null) {
                expander.setSrc(toUnpack);
                expander.setDest(toUnpack.getParentFile());
                expander.perform();
            } else if (toUnpack.getAbsolutePath().toLowerCase().endsWith("zip")) {
                try {
                    FileTools.unZipFiles(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            } else { // gzip.
                try {
                    FileTools.unGzipFile(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return Boolean.TRUE;
        }

    });
    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(future);
    executor.shutdown();

    StopWatch s = new StopWatch();
    s.start();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            future.cancel(true);
            return;
        }
        log.info("Unpacking archive ... " + Math.floor(s.getTime() / 1000.0) + " seconds elapsed");
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

protected long runWithTimeout(MutationTestRunnable r) {
    long[] preIds = threadMxBean.getAllThreadIds();
    FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r));
    Thread thread = new Thread(future);
    thread.setDaemon(true);//w  w w.j  ava2 s  .  co m
    logger.debug("Start  test: ");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    thread.start();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        future.get(timeout, TimeUnit.SECONDS);
        logger.debug("Second timeout");
    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            capturedThrowable.printStackTrace(new PrintStream(out));
            logger.debug(
                    "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable);
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE
                + "Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();
    if (!checkAllFinished(preIds)) {
        if (configuration.useThreadStop()) {
            stopThreads(preIds);
        } else {
            shutDown(r, stopWatch);
        }
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:ubic.gemma.core.loader.expression.geo.GeoFamilyParser.java

@Override
public void parse(InputStream is) throws IOException {
    if (is == null) {
        throw new IOException("Inputstream was null");
    }/*from w w  w. j  a  v  a2  s  .com*/

    if (is.available() == 0) {
        throw new IOException("No bytes to read from the input stream.");
    }

    try (final BufferedReader dis = new BufferedReader(new InputStreamReader(is))) {

        GeoFamilyParser.log.debug("Parsing....");

        final ExecutorService executor = Executors.newSingleThreadExecutor();

        FutureTask<Exception> future = new FutureTask<>(new Callable<Exception>() {
            @Override
            public Exception call() {
                try {
                    GeoFamilyParser.this.doParse(dis);
                    dis.close();
                    return null;
                } catch (Exception e) {
                    GeoFamilyParser.log.error(e, e);
                    return e;
                }
            }
        });

        executor.execute(future);
        executor.shutdown();

        while (!future.isDone() && !future.isCancelled()) {
            try {
                TimeUnit.SECONDS.sleep(5L);
            } catch (InterruptedException e) {
                // probably cancelled.
                dis.close();
                return;
            }
            GeoFamilyParser.log.info(parsedLines + " lines parsed.");
        }

        try {
            Exception e = future.get();
            if (e != null) {
                GeoFamilyParser.log.error(e.getMessage());
                throw new RuntimeException(e.getCause());
            }
        } catch (ExecutionException e) {
            throw new RuntimeException("Parse failed", e.getCause());
        } catch (java.util.concurrent.CancellationException e) {
            throw new RuntimeException("Parse was cancelled", e.getCause());
        } catch (InterruptedException e) {
            throw new RuntimeException("Parse was interrupted", e.getCause());
        }

        executor.shutdownNow();

        assert future.isDone();
        // assert executor.isTerminated();

        GeoFamilyParser.log.info("Done parsing.");
    }
}

From source file:ubic.gemma.loader.expression.geo.GeoFamilyParser.java

@Override
public void parse(InputStream is) throws IOException {
    if (is == null) {
        throw new IOException("Inputstream was null");
    }//ww w  .j  a  va2 s  . c om

    if (is.available() == 0) {
        throw new IOException("No bytes to read from the input stream.");
    }

    final BufferedReader dis = new BufferedReader(new InputStreamReader(is));

    log.debug("Parsing....");

    final ExecutorService executor = Executors.newSingleThreadExecutor();

    FutureTask<Exception> future = new FutureTask<Exception>(new Callable<Exception>() {
        @Override
        public Exception call() {
            try {
                return doParse(dis);
            } catch (Exception e) {
                log.error(e, e);
                return e;
            }

        }
    });

    executor.execute(future);
    executor.shutdown();

    while (!future.isDone() && !future.isCancelled()) {
        try {
            TimeUnit.SECONDS.sleep(5L);
        } catch (InterruptedException e) {
            // probably cancelled.
            return;
        }
        log.info(parsedLines + " lines parsed.");
    }

    try {
        Exception e = future.get();
        if (e != null) {
            log.error(e.getMessage());
            throw new RuntimeException(e.getCause());
        }
    } catch (ExecutionException e) {
        throw new RuntimeException("Parse failed", e.getCause());
    } catch (java.util.concurrent.CancellationException e) {
        throw new RuntimeException("Parse was cancelled", e.getCause());
    } catch (InterruptedException e) {
        throw new RuntimeException("Parse was interrupted", e.getCause());
    }

    executor.shutdownNow();

    assert future.isDone();
    // assert executor.isTerminated();

    log.info("Done parsing.");
}

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//from w  ww  . j  a va  2  s.c  o  m
 * @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;
}