Example usage for java.util.concurrent ExecutionException getCause

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

Introduction

In this page you can find the example usage for java.util.concurrent ExecutionException 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.apache.hadoop.hbase.tool.LoadIncrementalHFiles.java

/**
 * This takes the LQI's grouped by likely regions and attempts to bulk load them. Any failures are
 * re-queued for another pass with the groupOrSplitPhase.
 * <p>//from   w  w  w.  jav a 2 s . com
 * protected for testing.
 */
@VisibleForTesting
protected void bulkLoadPhase(Table table, Connection conn, ExecutorService pool, Deque<LoadQueueItem> queue,
        Multimap<ByteBuffer, LoadQueueItem> regionGroups, boolean copyFile,
        Map<LoadQueueItem, ByteBuffer> item2RegionMap) throws IOException {
    // atomically bulk load the groups.
    Set<Future<List<LoadQueueItem>>> loadingFutures = new HashSet<>();
    for (Entry<ByteBuffer, ? extends Collection<LoadQueueItem>> e : regionGroups.asMap().entrySet()) {
        byte[] first = e.getKey().array();
        Collection<LoadQueueItem> lqis = e.getValue();

        ClientServiceCallable<byte[]> serviceCallable = buildClientServiceCallable(conn, table.getName(), first,
                lqis, copyFile);

        Callable<List<LoadQueueItem>> call = new Callable<List<LoadQueueItem>>() {
            @Override
            public List<LoadQueueItem> call() throws Exception {
                List<LoadQueueItem> toRetry = tryAtomicRegionLoad(serviceCallable, table.getName(), first,
                        lqis);
                return toRetry;
            }
        };
        if (item2RegionMap != null) {
            for (LoadQueueItem lqi : lqis) {
                item2RegionMap.put(lqi, e.getKey());
            }
        }
        loadingFutures.add(pool.submit(call));
    }

    // get all the results.
    for (Future<List<LoadQueueItem>> future : loadingFutures) {
        try {
            List<LoadQueueItem> toRetry = future.get();

            if (item2RegionMap != null) {
                for (LoadQueueItem lqi : toRetry) {
                    item2RegionMap.remove(lqi);
                }
            }
            // LQIs that are requeued to be regrouped.
            queue.addAll(toRetry);

        } catch (ExecutionException e1) {
            Throwable t = e1.getCause();
            if (t instanceof IOException) {
                // At this point something unrecoverable has happened.
                // TODO Implement bulk load recovery
                throw new IOException("BulkLoad encountered an unrecoverable problem", t);
            }
            LOG.error("Unexpected execution exception during bulk load", e1);
            throw new IllegalStateException(t);
        } catch (InterruptedException e1) {
            LOG.error("Unexpected interrupted exception during bulk load", e1);
            throw (InterruptedIOException) new InterruptedIOException().initCause(e1);
        }
    }
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Called when a ScheduledTask ends its execution. See afterExecute.
 *//*from  w w  w .  j  a  v  a 2s  .c  o m*/
protected void afterScheduledTaskExecution(Runnable r, Throwable t) {
    super.afterExecute(r, t);

    ScheduledTaskWrapper scheduledTask = null;
    Lock handlingTaskLock = null;

    if (r instanceof ScheduledFuture) {
        ScheduledFuture scheduledFuture = (ScheduledFuture) r;
        synchronized (scheduledFutures) {
            scheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture);

            if (scheduledTask != null) {
                handlingTaskLock = getHandlingTaskLock(scheduledTask.getId());
                handlingTaskLock.lock();
            }
        }
        //
        // Bear in mind that here the scheduledTask could be null if the scheduledFuture
        // has been cancelled and removed from the scheduledFutures map.
        //
        if (log.isTraceEnabled()) {
            if (scheduledTask == null) {
                log.trace("Scheduled task null for: " + r + ". Is it cancelled ? "
                        + scheduledFuture.isCancelled());
            }
        }

        try {
            if (scheduledFuture.isDone()) {
                scheduledFuture.get();
            }
        } catch (InterruptedException ie) {
        } catch (ExecutionException ee) {
            //
            // This is done to retrieve the possible exception thrown by the
            // task
            //
            Throwable realThrowable = ee.getCause();

            if (scheduledTask != null) {

                log.error("Task '" + scheduledTask + "' throws an uncaught exception. "
                        + "The task will be rescheduled", realThrowable);
                try {
                    scheduledTask.shutdown();
                } catch (TaskException ex) {
                    log.error("Error shutting down scheduled task '" + scheduledTask + "'", ex);
                }

                scheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN);

                synchronized (scheduledFutures) {
                    //
                    // Any time we remove the scheduledTask from scheduledFutures,
                    // we try to remove the scheduledFuture from the queue. This
                    // is not really needed because after a while this is performed
                    // automatically but in this way we keep scheduledFutures and
                    // the queue in sync
                    //
                    if (scheduledFuture instanceof Runnable) {
                        super.remove((Runnable) scheduledFuture);
                    }
                    scheduledFutures.remove(scheduledTask);
                }

                //
                // The task will be rescheduled using the period as delay
                // because otherwise a new execution is performed asap
                //
                scheduleTask(scheduledTask, scheduledTask.getPeriod());

            } else {
                log.error("Uncaught exception thrown by: " + scheduledFuture
                        + ". This ScheduledFuture seems not relative to a ScheduleTask"
                        + " so nothing will be rescheduled (it could be about "
                        + " to an already cancelled task)", realThrowable);
            }

        } catch (CancellationException ce) {
        } finally {
            if (handlingTaskLock != null) {
                handlingTaskLock.unlock();
            }
            handlingScheduledExecutionTimeInformation(scheduledTask);
            LogContext.clear();
        }
    }
}

From source file:org.openspaces.grid.gsm.rebalancing.DefaultRebalancingSlaEnforcementEndpoint.java

private void cleanFutureStatelessDeployments() throws RebalancingSlaEnforcementInProgressException {

    while (true) {

        FutureStatelessProcessingUnitInstance future = state.removeOneDoneFutureStatelessDeployments(pu);

        if (future == null) {
            // no more done futures
            break;
        }//w w w  .  j  av a2 s.  c  om

        Throwable throwable = null;

        try {
            ProcessingUnitInstance puInstance = future.get();
            logger.info("Processing unit instance deployment completed successfully "
                    + RebalancingUtils.puInstanceToString(puInstance));

        } catch (ExecutionException e) {
            throwable = e.getCause();
        } catch (TimeoutException e) {
            throwable = e;
        }

        if (throwable != null) {
            state.addFailedStatelessDeployment(future);
            throwFutureProcessingUnitInstanceException(throwable);
        }
    }

    cleanFailedFutureStatelessDeployments();
}

From source file:org.openspaces.grid.gsm.rebalancing.DefaultRebalancingSlaEnforcementEndpoint.java

private void cleanFutureStatefulDeployments() throws RebalancingSlaEnforcementInProgressException {

    while (true) {

        FutureStatefulProcessingUnitInstance future = state.removeOneDoneFutureStatefulDeployments(pu);

        if (future == null) {
            // no more done futures
            break;
        }//  w  w  w .  j a  v  a2s.  c  o m

        Throwable throwable = null;

        try {
            ProcessingUnitInstance puInstance = future.get();
            logger.info("Processing unit instance deployment completed successfully "
                    + RebalancingUtils.puInstanceToString(puInstance));

        } catch (ExecutionException e) {
            throwable = e.getCause();
        } catch (TimeoutException e) {
            throwable = e;
        }

        if (throwable != null) {
            state.addFailedStatefulDeployment(future);
            throwFutureProcessingUnitInstanceException(throwable);
        }

    }

    cleanFailedFutureStatefulDeployments();
}

From source file:org.apache.hadoop.hbase.PerformanceEvaluation.java

private void doLocalClients(final Class<? extends Test> cmd, final TestOptions opts)
        throws IOException, InterruptedException {
    Future<Long>[] threads = new Future[opts.numClientThreads];
    long[] timings = new long[opts.numClientThreads];
    ExecutorService pool = Executors.newFixedThreadPool(opts.numClientThreads,
            new ThreadFactoryBuilder().setNameFormat("TestClient-%s").build());
    for (int i = 0; i < threads.length; i++) {
        final int index = i;
        threads[i] = pool.submit(new Callable<Long>() {
            @Override/* ww  w .  ja v  a 2 s  . c  o  m*/
            public Long call() throws Exception {
                TestOptions threadOpts = new TestOptions(opts);
                threadOpts.startRow = index * threadOpts.perClientRunRows;
                long elapsedTime = runOneClient(cmd, getConf(), threadOpts, new Status() {
                    public void setStatus(final String msg) throws IOException {
                        LOG.info(msg);
                    }
                });
                LOG.info("Finished in " + elapsedTime + "ms over " + threadOpts.perClientRunRows + " rows");
                return elapsedTime;
            }
        });
    }
    pool.shutdown();
    for (int i = 0; i < threads.length; i++) {
        try {
            timings[i] = threads[i].get();
        } catch (ExecutionException e) {
            throw new IOException(e.getCause());
        }
    }
    final String test = cmd.getSimpleName();
    LOG.info("[" + test + "] Summary of timings (ms): " + Arrays.toString(timings));
    Arrays.sort(timings);
    long total = 0;
    for (long timing : timings) {
        total += timing;
    }
    LOG.info("[" + test + "]" + "\tMin: " + timings[0] + "ms" + "\tMax: " + timings[timings.length - 1] + "ms"
            + "\tAvg: " + (total / timings.length) + "ms");
}

From source file:com.github.helenusdriver.driver.impl.StatementImpl.java

/**
 * {@inheritDoc}//from  w  ww .  j  ava2 s  .c  o  m
 *
 * @author paouelle
 *
 * @see com.github.helenusdriver.driver.GenericStatement#execute()
 */
@SuppressWarnings("unchecked")
@Override
public R execute() {
    final ListenableFuture<R> future = executeAsync();

    if (future instanceof ObjectSetFuture) {
        return (R) ((ObjectSetFuture<?>) future).getUninterruptibly();
    }
    if (future instanceof VoidFuture) {
        return (R) ((VoidFuture) future).getUninterruptibly();
    }
    if (future instanceof ResultSetFuture) {
        return (R) ((ResultSetFuture) future).getUninterruptibly();
    }
    // should not get here though! but in case ...
    try {
        return Uninterruptibles.getUninterruptibly(future);
    } catch (ExecutionException e) {
        // extracted from DefaultResultSet.extractCauseFromExecutionException()
        // --------------------------------------------------------------------
        // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
        // created on the I/O thread receiving the response. Which means that the stacktrace associated
        // with said cause will make no mention of the current thread. This is painful for say, finding
        // out which execute() statement actually raised the exception. So instead, we re-create the
        // exception.
        if (e.getCause() instanceof DriverException) {
            throw ((DriverException) e.getCause()).copy();
        }
        throw new DriverInternalError("Unexpected exception thrown", e.getCause());
    }
}

From source file:org.apache.hadoop.dfs.Balancer.java

private long dispatchBlockMoves() throws InterruptedException {
    long bytesLastMoved = bytesMoved.get();
    Future<?>[] futures = new Future<?>[sources.size()];
    int i = 0;/*from  w w w  . j a v a2s  . c  om*/
    for (Source source : sources) {
        futures[i++] = dispatcherExecutor.submit(source.new BlockMoveDispatcher());
    }

    // wait for all dispatcher threads to finish
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException e) {
            LOG.warn("Dispatcher thread failed", e.getCause());
        }
    }

    // wait for all block moving to be done
    waitForMoveCompletion();

    return bytesMoved.get() - bytesLastMoved;
}

From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java

private IOException toIOException(ExecutionException e) {
    final Throwable cause = e.getCause();
    if (cause instanceof IOException) {
        return (IOException) cause;
    } else {/*from  w  w w. ja  va2s.  co  m*/
        return new IOException(cause);
    }
}

From source file:org.dcache.chimera.JdbcFs.java

@Override
public FsStat getFsStat() throws ChimeraFsException {
    try {/* w  w  w.  ja  v a  2  s  . c  om*/
        return _fsStatCache.get(DUMMY_KEY);
    } catch (ExecutionException e) {
        Throwable t = e.getCause();
        Throwables.propagateIfPossible(t, ChimeraFsException.class);
        throw new ChimeraFsException(t.getMessage(), t);
    }
}

From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java

@Test(expected = DockerTimeoutException.class)
public void testConnectionRequestTimeout() throws Exception {
    final int connectionPoolSize = 1;
    final int callableCount = connectionPoolSize * 100;

    final ExecutorService executor = Executors.newCachedThreadPool();
    final CompletionService completion = new ExecutorCompletionService(executor);

    // Spawn and wait on many more containers than the connection pool size.
    // This should cause a timeout once the connection pool is exhausted.

    final DockerClient dockerClient = DefaultDockerClient.fromEnv().connectionPoolSize(connectionPoolSize)
            .build();/*from w  w w .j  av a  2 s  .c  o m*/
    try {
        // Create container
        final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX_LATEST)
                .cmd("sh", "-c", "while :; do sleep 1; done").build();
        final String name = randomName();
        final ContainerCreation creation = dockerClient.createContainer(config, name);
        final String id = creation.id();

        // Start the container
        dockerClient.startContainer(id);

        // Submit a bunch of waitContainer requests
        for (int i = 0; i < callableCount; i++) {
            completion.submit(new Callable<ContainerExit>() {
                @Override
                public ContainerExit call() throws Exception {
                    return dockerClient.waitContainer(id);
                }
            });
        }

        // Wait for the requests to complete or throw expected exception
        for (int i = 0; i < callableCount; i++) {
            try {
                completion.take().get();
            } catch (ExecutionException e) {
                Throwables.propagateIfInstanceOf(e.getCause(), DockerTimeoutException.class);
                throw e;
            }
        }
    } finally {
        executor.shutdown();
        dockerClient.close();
    }
}