Example usage for java.util.concurrent FutureTask isCancelled

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

Introduction

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

Prototype

public boolean isCancelled() 

Source Link

Usage

From source file:ubic.basecode.math.linalg.SingularValueDecomposition.java

/**
 * @param dm//from www .ja  v a 2s. com
 */
private void computeSVD(final DoubleMatrix2D dm) {
    /*
     * This fails to converge some times, we have to bail.
     */
    FutureTask<cern.colt.matrix.linalg.SingularValueDecomposition> svdFuture = new FutureTask<>(
            new Callable<cern.colt.matrix.linalg.SingularValueDecomposition>() {
                @Override
                public cern.colt.matrix.linalg.SingularValueDecomposition call() {
                    return new cern.colt.matrix.linalg.SingularValueDecomposition(dm);
                }
            });

    StopWatch timer = new StopWatch();
    timer.start();
    Executors.newSingleThreadExecutor().execute(svdFuture);

    while (!svdFuture.isDone() && !svdFuture.isCancelled()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ie) {
            throw new RuntimeException("SVD cancelled");
        }
        if (timer.getTime() > MAX_COMPUTE_TIME) {
            svdFuture.cancel(true);
            throw new RuntimeException("SVD failed to converge within " + MAX_COMPUTE_TIME + "ms, bailing");
        }
    }
    timer.stop();
    try {
        this.svd = svdFuture.get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }

    assert this.svd != null;
}

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");
    }/*  w w w . jav a  2  s . c  o m*/

    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.core.loader.util.fetcher.AbstractFetcher.java

/**
 * @param future future task/*  w ww .j  a v a  2  s .  c  o m*/
 * @return true if it finished normally, false if it was cancelled.
 */
protected boolean waitForDownload(FutureTask<Boolean> future) {
    StopWatch timer = new StopWatch();
    timer.start();
    long lastTime = timer.getTime();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            AbstractFetcher.log.info("Cancelling download");
            boolean cancelled = future.cancel(true);
            if (cancelled) {
                AbstractFetcher.log.info("Download stopped successfully.");
                return false;
            }
            throw new RuntimeException("Cancellation failed.");

        }

        if (AbstractFetcher.log.isInfoEnabled() && timer.getTime() > (lastTime + 2000L)) {
            AbstractFetcher.log.info("Waiting ... " + timer.getTime() + "ms elapsed....");
        }
    }
    return true;
}

From source file:ubic.gemma.core.loader.util.fetcher.AbstractFetcher.java

/**
 * @param future       future task/*from www  . ja v a 2  s .  c om*/
 * @param expectedSize expected size
 * @param outputFile   output file
 * @return true if it finished normally, false if it was cancelled.
 */
protected boolean waitForDownload(FutureTask<Boolean> future, long expectedSize, File outputFile) {
    int i = 0;
    long previousSize = 0;
    StopWatch idleTimer = new StopWatch();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            if (AbstractFetcher.log != null) {
                AbstractFetcher.log.info("Cancelling download");
            }
            boolean cancelled = future.cancel(true);
            if (cancelled) {
                return false;
            }

            // double check...
            if (future.isCancelled() || future.isDone()) {
                return false;
            }

            if (AbstractFetcher.log != null) {
                AbstractFetcher.log.error(
                        "Cancellation of actual download might not have happened? Task says it was not cancelled: "
                                + future);
            }

            return false;

        }

        /*
         * Avoid logging too much. If we're waiting for a long download, reduce frequency of updates.
         */
        if (outputFile.length() < expectedSize
                && (i < AbstractFetcher.NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY
                        || i % AbstractFetcher.NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY == 0)) {

            double percent = 100.00 * outputFile.length() / expectedSize;

            // can cause npe error, breaking hot deploy
            if (AbstractFetcher.log != null && AbstractFetcher.log.isInfoEnabled()) {
                AbstractFetcher.log.info((outputFile.length() + (expectedSize > 0 ? "/" + expectedSize : "")
                        + " bytes read (" + String.format("%.1f", percent) + "%)"));
            }

            if (previousSize == outputFile.length()) {
                /*
                 * Possibly consider bailing after a while.
                 */
                if (idleTimer.getTime() > AbstractFetcher.STALLED_BAIL_TIME_LIMIT) {
                    if (AbstractFetcher.log != null) {
                        AbstractFetcher.log.warn("Download does not seem to be happening, bailing");
                    }
                    return false;
                }
                if (idleTimer.getTime() == 0)
                    idleTimer.start();
            } else {
                idleTimer.reset();
                idleTimer.start();
            }
        }

        //            if ( outputFile.length() >= expectedSize ) {
        //                // no special action, it will finish soon enough.
        //            }

        previousSize = outputFile.length();

        i++;
    }
    if (i == 0)
        if (AbstractFetcher.log != null) {
            AbstractFetcher.log.info("File with size " + outputFile.length() + " bytes.");
        }
    return true;
}

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  a v  a  2 s. com
        @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.expression.geo.GeoFamilyParser.java

@Override
public void parse(InputStream is) throws IOException {
    if (is == null) {
        throw new IOException("Inputstream was null");
    }/*w w w  .jav a  2s  .co  m*/

    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:ubic.gemma.loader.util.fetcher.AbstractFetcher.java

/**
 * @param future/*ww w. ja v a2s.co m*/
 * @return true if it finished normally, false if it was cancelled.
 */
protected boolean waitForDownload(FutureTask<Boolean> future) {
    StopWatch timer = new StopWatch();
    timer.start();
    long lastTime = timer.getTime();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            log.info("Cancelling download");
            boolean cancelled = future.cancel(true);
            if (cancelled) {
                log.info("Download stopped successfully.");
                return false;
            }
            throw new RuntimeException("Cancellation failed.");

        }

        if (log.isInfoEnabled() && timer.getTime() > (lastTime + 2000L)) {
            log.info("Waiting ... " + timer.getTime() + "ms elapsed....");
        }
    }
    return true;
}

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

/**
 * @param future/* www .j  a va  2  s .c o m*/
 * @param expectedSize
 * @param outputFileName
 * @return true if it finished normally, false if it was cancelled.
 */
protected boolean waitForDownload(FutureTask<Boolean> future, long expectedSize, File outputFile) {
    int iters = 0;
    long previousSize = 0;
    StopWatch idleTimer = new StopWatch();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            log.info("Cancelling download");
            boolean cancelled = future.cancel(true);
            if (cancelled) {
                return false;
            }

            // double check...
            if (future.isCancelled() || future.isDone()) {
                return false;
            }

            log.error("Cancellation of actual download might not have happend? Task says it was not cancelled: "
                    + future);

            return false;

        }

        /*
         * Avoid logging too much. If we're waiting for a long download, reduce frequency of updates.
         */
        if (outputFile.length() < expectedSize
                && (iters < NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY
                        || iters % NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY == 0)) {

            double percent = 100.00 * outputFile.length() / expectedSize;

            // can cause npe error, breaking hot deploy
            if (log != null && log.isInfoEnabled()) {
                log.info((outputFile.length() + (expectedSize > 0 ? "/" + expectedSize : "") + " bytes read ("
                        + String.format("%.1f", percent) + "%)"));
            }

            if (previousSize == outputFile.length()) {
                /*
                 * Possibly consider bailing after a while.
                 */
                if (idleTimer.getTime() > STALLED_BAIL_TIME_LIMIT) {
                    log.warn("Download does not seem to be happening, bailing");
                    return false;
                }
                if (idleTimer.getTime() == 0)
                    idleTimer.start();
            } else {
                idleTimer.reset();
                idleTimer.start();
            }
        }

        if (outputFile.length() >= expectedSize) {
            // no special action, it will finish soon enough.
        }

        previousSize = outputFile.length();

        iters++;
    }
    if (iters == 0)
        log.info("File with size " + outputFile.length() + " bytes.");
    return true;
}

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

/**
 * @param newDir//  w w  w  .  ja  va 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");
    }
}