Example usage for java.util.concurrent CancellationException getCause

List of usage examples for java.util.concurrent CancellationException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

/**
 * @since 3.6/*from  w  ww  .ja va 2s. c  om*/
 */
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
    // check for legacy reasons
    SubMonitor subMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(null);

    Future<T> future = CommonsHttpPlugin.getExecutorService().submit(request);
    while (true) {
        if (monitor.isCanceled()) {
            request.abort();

            // wait for executor to finish
            future.cancel(false);
            try {
                if (!future.isCancelled()) {
                    future.get();
                }
            } catch (CancellationException e) {
                // ignore
            } catch (InterruptedException e) {
                // ignore
            } catch (ExecutionException e) {
                // ignore
            }
            throw new OperationCanceledException();
        }

        try {
            return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException ignored) {
        }

        subMonitor.setWorkRemaining(20);
        subMonitor.worked(1);
    }
}

From source file:org.t2framework.commons.util.LazyLoadingReference.java

 public T get() throws IllegalStateException {
   while (true) {
      WeakReference<Future<T>> ref = reference.get();
      boolean valid = true;
      if (ref == null) {
         FutureTask<T> f = new FutureTask<T>(new Callable<T>() {
            @Override//  ww  w.j  a  va2  s. c o  m
            public T call() throws Exception {
               return factory.create();
            }
         });
         ref = new WeakReference<Future<T>>(f);
         if (valid = reference.compareAndSet(null, ref)) {
            f.run();
         }
      }
      if (valid) {
         try {
            Future<T> f = ref.get();
            if (f != null) {
               return f.get();
            } else {
               reference.compareAndSet(ref, null);
            }
         } catch (CancellationException e) {
            reference.compareAndSet(ref, null);
         } catch (ExecutionException e) {
            throw new IllegalStateException(e.getCause());
         } catch (Exception e) {
            throw new IllegalStateException(e);
         }
      }
   }
}

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

/**
 * Get/Parse a template source./*from w ww.  j a v  a 2 s . co  m*/
 *
 * @param source The template source.
 * @param parser The parser.
 * @return A Handlebars template.
 * @throws IOException If we can't read input.
 */
private Template cacheGet(final TemplateSource source, final Parser parser) throws IOException {
    notNull(source, "The source is required.");
    notNull(parser, "The parser is required.");

    boolean interrupted = false;

    FutureTask<Pair<TemplateSource, Template>> futureTask = newTask(source, parser);
    try {
        while (true) {
            Future<Pair<TemplateSource, Template>> future = cache.get(source);
            try {
                if (future == null) {
                    logger.debug("Loading: {}", source);
                    future = putIfAbsent(source, futureTask);
                } else if (source.lastModified() != future.get().getKey().lastModified()) {
                    evict(source);
                    logger.debug("Reloading: {}", source);
                    future = putIfAbsent(source, futureTask);
                } else {
                    logger.debug("Found in cache: {}", source);
                }
                Pair<TemplateSource, Template> entry = future.get();
                return entry.getValue();
            } catch (CancellationException ex) {
                cache.remove(source, future);
            } catch (InterruptedException ex) {
                // fall through and retry
                interrupted = true;
            } catch (ExecutionException ex) {
                if (future != null) {
                    cache.remove(source, future);
                }
                throw launderThrowable(source, ex.getCause());
            }
        }
    } finally {
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.spotify.heroic.HeroicCore.java

/**
 * Setup a fixed thread pool executor that correctly handles unhandled exceptions.
 *
 * @param threads Number of threads to configure.
 *///from ww  w .  jav a  2 s  .c  o m
private ExecutorService setupExecutor(final int threads) {
    return new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
            new ThreadFactoryBuilder().setNameFormat("heroic-core-%d")
                    .setUncaughtExceptionHandler(uncaughtExceptionHandler).build()) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);

            if (t == null && (r instanceof Future<?>)) {
                try {
                    ((Future<?>) r).get();
                } catch (CancellationException e) {
                    t = e;
                } catch (ExecutionException e) {
                    t = e.getCause();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

            if (t != null) {
                if (log.isErrorEnabled()) {
                    log.error("Unhandled exception caught in core executor", t);
                    log.error("Exiting (code=2)");
                } else {
                    System.err.println("Unhandled exception caught in core executor");
                    System.err.println("Exiting (code=2)");
                    t.printStackTrace(System.err);
                }

                System.exit(2);
            }
        }
    };
}

From source file:org.apache.blur.command.BaseCommandManager.java

@SuppressWarnings("unchecked")
public Response reconnect(Long instanceExecutionId) throws IOException, TimeoutException {
    Future<Response> future = (Future<Response>) _driverRunningMap.get(instanceExecutionId);
    if (future == null) {
        throw new IOException(
                "Execution instance id [" + instanceExecutionId + "] did not find any executing commands.");
    }/*  w w  w.  java2 s  . c o  m*/
    try {
        return future.get(_connectionTimeout, TimeUnit.MILLISECONDS);
    } catch (CancellationException e) {
        throw new IOException(e);
    } catch (InterruptedException e) {
        throw new IOException(e);
    } catch (ExecutionException e) {
        throw new IOException(e.getCause());
    } catch (java.util.concurrent.TimeoutException e) {
        LOG.info("Timeout of command [{0}]", instanceExecutionId);
        throw new TimeoutException(instanceExecutionId);
    }
}

From source file:org.apache.blur.command.BaseCommandManager.java

protected Response submitDriverCallable(Callable<Response> callable, Command<?> commandExecuting)
        throws IOException, TimeoutException, ExceptionCollector {
    Future<Response> future = _executorServiceDriver.submit(callable);
    Long instanceExecutionId = getInstanceExecutionId();
    _driverRunningMap.put(instanceExecutionId,
            new ResponseFuture<Response>(_runningCacheTombstoneTime, future, commandExecuting));
    try {//from   w w w  .j a v  a  2s.c om
        return future.get(_connectionTimeout, TimeUnit.MILLISECONDS);
    } catch (CancellationException e) {
        throw new IOException(e);
    } catch (InterruptedException e) {
        throw new IOException(e);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof ExceptionCollector) {
            throw (ExceptionCollector) cause;
        }
        throw new IOException(cause);
    } catch (java.util.concurrent.TimeoutException e) {
        LOG.info("Timeout of command [{0}]", instanceExecutionId);
        throw new TimeoutException(instanceExecutionId);
    }
}

From source file:org.apache.hadoop.hbase.index.builder.IndexBuildManager.java

public Collection<Pair<Mutation, byte[]>> getIndexUpdate(
        MiniBatchOperationInProgress<Pair<Mutation, Integer>> miniBatchOp,
        Collection<? extends Mutation> mutations) throws Throwable {
    // notify the delegate that we have started processing a batch
    this.delegate.batchStarted(miniBatchOp);

    // parallelize each mutation into its own task
    // each task is cancelable via two mechanisms: (1) underlying HRegion is closing (which would
    // fail lookups/scanning) and (2) by stopping this via the #stop method. Interrupts will only be
    // acknowledged on each thread before doing the actual lookup, but after that depends on the
    // underlying builder to look for the closed flag.
    TaskBatch<Collection<Pair<Mutation, byte[]>>> tasks = new TaskBatch<Collection<Pair<Mutation, byte[]>>>(
            mutations.size());/* ww  w.ja  va  2 s  .  c  om*/
    for (final Mutation m : mutations) {
        tasks.add(new Task<Collection<Pair<Mutation, byte[]>>>() {

            @Override
            public Collection<Pair<Mutation, byte[]>> call() throws IOException {
                return delegate.getIndexUpdate(m);
            }

        });
    }
    List<Collection<Pair<Mutation, byte[]>>> allResults = null;
    try {
        allResults = pool.submitUninterruptible(tasks);
    } catch (CancellationException e) {
        throw e;
    } catch (ExecutionException e) {
        LOG.error("Found a failed index update!");
        throw e.getCause();
    }

    // we can only get here if we get successes from each of the tasks, so each of these must have a
    // correct result
    Collection<Pair<Mutation, byte[]>> results = new ArrayList<Pair<Mutation, byte[]>>();
    for (Collection<Pair<Mutation, byte[]>> result : allResults) {
        assert result != null : "Found an unsuccessful result, but didn't propagate a failure earlier";
        results.addAll(result);
    }

    return results;
}

From source file:org.apache.phoenix.hbase.index.builder.IndexBuildManager.java

public Collection<Pair<Mutation, byte[]>> getIndexUpdate(MiniBatchOperationInProgress<Mutation> miniBatchOp,
        Collection<? extends Mutation> mutations) throws Throwable {
    // notify the delegate that we have started processing a batch
    this.delegate.batchStarted(miniBatchOp);

    // parallelize each mutation into its own task
    // each task is cancelable via two mechanisms: (1) underlying HRegion is closing (which would
    // fail lookups/scanning) and (2) by stopping this via the #stop method. Interrupts will only be
    // acknowledged on each thread before doing the actual lookup, but after that depends on the
    // underlying builder to look for the closed flag.
    TaskBatch<Collection<Pair<Mutation, byte[]>>> tasks = new TaskBatch<Collection<Pair<Mutation, byte[]>>>(
            mutations.size());//from   w w w.  j  a  v  a 2  s  . c  o  m
    for (final Mutation m : mutations) {
        tasks.add(new Task<Collection<Pair<Mutation, byte[]>>>() {

            @Override
            public Collection<Pair<Mutation, byte[]>> call() throws IOException {
                return delegate.getIndexUpdate(m);
            }

        });
    }
    List<Collection<Pair<Mutation, byte[]>>> allResults = null;
    try {
        allResults = pool.submitUninterruptible(tasks);
    } catch (CancellationException e) {
        throw e;
    } catch (ExecutionException e) {
        LOG.error("Found a failed index update!");
        throw e.getCause();
    }

    // we can only get here if we get successes from each of the tasks, so each of these must have a
    // correct result
    Collection<Pair<Mutation, byte[]>> results = new ArrayList<Pair<Mutation, byte[]>>();
    for (Collection<Pair<Mutation, byte[]>> result : allResults) {
        assert result != null : "Found an unsuccessful result, but didn't propagate a failure earlier";
        results.addAll(result);
    }

    return results;
}

From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java

/**
 * Used by batch import and export to wait for queued tasks to complete. Handles fail-fast behavior
 * if any of the tasks threw and exception by canceling all queued futures and logging a summary of
 * the failures. All completed futures are removed from the queue.
 *
 * @param futures Queued futures to check for completeness
 * @param wait If true it will wait for all futures to complete, if false only check for completed futures
 * @return a list of futures that either threw exceptions or timed out
 *///from  w w  w. ja va 2  s.co m
protected List<FutureHolder<?>> waitForFutures(final Queue<? extends FutureHolder<?>> futures,
        final PrintWriter reportWriter, final File reportDirectory, final boolean wait)
        throws InterruptedException {

    final List<FutureHolder<?>> failedFutures = new LinkedList<FutureHolder<?>>();

    for (Iterator<? extends FutureHolder<?>> futuresItr = futures.iterator(); futuresItr.hasNext();) {
        final FutureHolder<?> futureHolder = futuresItr.next();

        //If waiting, or if not waiting but the future is already done do the get
        final Future<?> future = futureHolder.getFuture();
        if (wait || (!wait && future.isDone())) {
            futuresItr.remove();

            try {
                //Don't bother doing a get() on canceled futures
                if (!future.isCancelled()) {
                    if (this.maxWait > 0) {
                        future.get(this.maxWait, this.maxWaitTimeUnit);
                    } else {
                        future.get();
                    }

                    reportWriter.printf(REPORT_FORMAT, "SUCCESS", futureHolder.getDescription(),
                            futureHolder.getExecutionTimeMillis());
                }
            } catch (CancellationException e) {
                //Ignore cancellation exceptions
            } catch (ExecutionException e) {
                logger.error("Failed: " + futureHolder);

                futureHolder.setError(e);
                failedFutures.add(futureHolder);
                reportWriter.printf(REPORT_FORMAT, "FAIL", futureHolder.getDescription(),
                        futureHolder.getExecutionTimeMillis());

                try {
                    final String dataReportName = SafeFilenameUtils.makeSafeFilename(
                            futureHolder.getDataType() + "_" + futureHolder.getDataName() + ".txt");
                    final File dataReportFile = new File(reportDirectory, dataReportName);
                    final PrintWriter dataReportWriter = new PrintWriter(
                            new BufferedWriter(new FileWriter(dataReportFile)));
                    try {
                        dataReportWriter.println(
                                "FAIL: " + futureHolder.getDataType() + " - " + futureHolder.getDataName());
                        dataReportWriter.println(
                                "--------------------------------------------------------------------------------");
                        e.getCause().printStackTrace(dataReportWriter);
                    } finally {
                        IOUtils.closeQuietly(dataReportWriter);
                    }
                } catch (Exception re) {
                    logger.warn("Failed to write error report for failed " + futureHolder
                            + ", logging root failure here", e.getCause());
                }
            } catch (TimeoutException e) {
                logger.warn("Failed: " + futureHolder);

                futureHolder.setError(e);
                failedFutures.add(futureHolder);
                future.cancel(true);
                reportWriter.printf(REPORT_FORMAT, "TIMEOUT", futureHolder.getDescription(),
                        futureHolder.getExecutionTimeMillis());
            }
        }
    }

    return failedFutures;
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

/**
 * @since 3.0/*from w  w  w . ja  v  a  2s.c o  m*/
 */
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
    // check for legacy reasons
    SubMonitor subMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(null);

    Future<T> future = CommonsNetPlugin.getExecutorService().submit(request);
    while (true) {
        if (monitor.isCanceled()) {
            request.abort();

            // wait for executor to finish
            future.cancel(false);
            try {
                if (!future.isCancelled()) {
                    future.get();
                }
            } catch (CancellationException e) {
                // ignore
            } catch (InterruptedException e) {
                // ignore
            } catch (ExecutionException e) {
                // ignore
            }
            throw new OperationCanceledException();
        }

        try {
            return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException ignored) {
        }

        subMonitor.setWorkRemaining(20);
        subMonitor.worked(1);
    }
}