Search in sources :

Example 41 with CancellationException

use of java.util.concurrent.CancellationException in project jetty.project by eclipse.

the class FuturePromise method cancel.

@Override
public boolean cancel(boolean mayInterruptIfRunning) {
    if (_done.compareAndSet(false, true)) {
        _result = null;
        _cause = new CancellationException();
        _latch.countDown();
        return true;
    }
    return false;
}
Also used : CancellationException(java.util.concurrent.CancellationException)

Example 42 with CancellationException

use of java.util.concurrent.CancellationException in project hive by apache.

the class JobRequestExecutor method execute.

/*
   * Executes job request operation. If thread pool is not created then job request is
   * executed in current thread itself.
   *
   * @param jobExecuteCallable
   *          Callable object to run the job request task.
   *
   */
public T execute(JobCallable<T> jobExecuteCallable) throws InterruptedException, TimeoutException, TooManyRequestsException, ExecutionException {
    /*
     * The callable shouldn't be null to execute. The thread pool also should be configured
     * to execute requests.
     */
    assert (jobExecuteCallable != null);
    assert (this.jobExecutePool != null);
    String type = this.requestType.toString().toLowerCase();
    String retryMessageForConcurrentRequests = "Please wait for some time before retrying " + "the operation. Please refer to the config " + concurrentRequestsConfigName + " to configure concurrent requests.";
    LOG.debug("Starting new " + type + " job request with time out " + this.requestExecutionTimeoutInSec + "seconds.");
    Future<T> future = null;
    try {
        future = this.jobExecutePool.submit(jobExecuteCallable);
    } catch (RejectedExecutionException rejectedException) {
        /*
       * Not able to find thread to execute the job request. Raise Busy exception and client
       * can retry the operation.
       */
        String tooManyRequestsExceptionMessage = "Unable to service the " + type + " job request as " + "templeton service is busy with too many " + type + " job requests. " + retryMessageForConcurrentRequests;
        LOG.warn(tooManyRequestsExceptionMessage);
        throw new TooManyRequestsException(tooManyRequestsExceptionMessage);
    }
    T result = null;
    try {
        result = this.requestExecutionTimeoutInSec > 0 ? future.get(this.requestExecutionTimeoutInSec, TimeUnit.SECONDS) : future.get();
    } catch (TimeoutException e) {
        /*
       * See if the execution thread has just completed operation and result is available.
       * If result is available then return the result. Otherwise, raise exception.
       */
        if ((result = tryGetJobResultOrSetJobStateFailed(jobExecuteCallable)) == null) {
            String message = this.requestType + " job request got timed out. Please wait for some time " + "before retrying the operation. Please refer to the config " + jobTimeoutConfigName + " to configure job request time out.";
            LOG.warn(message);
            /*
         * Throw TimeoutException to caller.
         */
            throw new TimeoutException(message);
        }
    } catch (InterruptedException e) {
        /*
       * See if the execution thread has just completed operation and result is available.
       * If result is available then return the result. Otherwise, raise exception.
       */
        if ((result = tryGetJobResultOrSetJobStateFailed(jobExecuteCallable)) == null) {
            String message = this.requestType + " job request got interrupted. Please wait for some time " + "before retrying the operation.";
            LOG.warn(message);
            /*
         * Throw TimeoutException to caller.
         */
            throw new InterruptedException(message);
        }
    } catch (CancellationException e) {
        /*
       * See if the execution thread has just completed operation and result is available.
       * If result is available then return the result. Otherwise, raise exception.
       */
        if ((result = tryGetJobResultOrSetJobStateFailed(jobExecuteCallable)) == null) {
            String message = this.requestType + " job request got cancelled and thread got interrupted. " + "Please wait for some time before retrying the operation.";
            LOG.warn(message);
            throw new InterruptedException(message);
        }
    } finally {
        /*
       * If the thread is still active and needs to be cancelled then cancel it. This may
       * happen in case task got interrupted, or timed out.
       */
        if (enableCancelTask) {
            cancelExecutePoolThread(future);
        }
    }
    LOG.debug("Completed " + type + " job request.");
    return result;
}
Also used : CancellationException(java.util.concurrent.CancellationException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 43 with CancellationException

use of java.util.concurrent.CancellationException in project hudson-2.x by hudson.

the class Request method callAsync.

/**
     * Makes an invocation but immediately returns without waiting for the completion
     * (AKA asynchronous invocation.)
     *
     * @param channel
     *      The channel from which the request will be sent.
     * @return
     *      The {@link Future} object that can be used to wait for the completion.
     * @throws IOException
     *      If there's an error during the communication.
     */
public final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOException {
    response = null;
    channel.pendingCalls.put(id, this);
    channel.send(this);
    return new hudson.remoting.Future<RSP>() {

        private volatile boolean cancelled;

        public boolean cancel(boolean mayInterruptIfRunning) {
            if (cancelled || isDone()) {
                return false;
            }
            cancelled = true;
            if (mayInterruptIfRunning) {
                try {
                    channel.send(new Cancel(id));
                } catch (IOException x) {
                    return false;
                }
            }
            return true;
        }

        public boolean isCancelled() {
            return cancelled;
        }

        public boolean isDone() {
            return isCancelled() || response != null;
        }

        public RSP get() throws InterruptedException, ExecutionException {
            synchronized (Request.this) {
                try {
                    while (response == null) {
                        if (isCancelled()) {
                            throw new CancellationException();
                        }
                        // wait until the response arrives
                        Request.this.wait();
                    }
                } catch (InterruptedException e) {
                    try {
                        channel.send(new Cancel(id));
                    } catch (IOException e1) {
                    // couldn't cancel. ignore.
                    }
                    throw e;
                }
                if (response.exception != null)
                    throw new ExecutionException(response.exception);
                return response.returnValue;
            }
        }

        public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            synchronized (Request.this) {
                if (response == null) {
                    if (isCancelled()) {
                        throw new CancellationException();
                    }
                    // wait until the response arrives
                    Request.this.wait(unit.toMillis(timeout));
                }
                if (response == null)
                    throw new TimeoutException();
                if (response.exception != null)
                    throw new ExecutionException(response.exception);
                return response.returnValue;
            }
        }
    };
}
Also used : CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 44 with CancellationException

use of java.util.concurrent.CancellationException in project PayFile by mikehearn.

the class Controller method download.

public void download(ActionEvent event) throws Exception {
    File destination = null;
    try {
        final PayFileClient.File downloadingFile = checkNotNull(selectedFile.get());
        if (downloadingFile.getPrice() > getBalance().longValue())
            throw new InsufficientMoneyException(BigInteger.valueOf(downloadingFile.getPrice() - getBalance().longValue()));
        // Ask the user where to put it.
        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setTitle("Select download directory");
        File directory = chooser.showDialog(Main.instance.mainWindow);
        if (directory == null)
            return;
        destination = new File(directory, downloadingFile.getFileName());
        FileOutputStream fileStream = new FileOutputStream(destination);
        final long startTime = System.currentTimeMillis();
        cancelBtn.setVisible(true);
        progressBarLabel.setText("Downloading " + downloadingFile.getFileName());
        // Make the UI update whilst the download is in progress: progress bar and balance label.
        ProgressOutputStream stream = new ProgressOutputStream(fileStream, downloadingFile.getSize());
        progressBar.progressProperty().bind(stream.progressProperty());
        Main.client.setOnPaymentMade((amt) -> Platform.runLater(this::refreshBalanceLabel));
        // Swap in the progress bar with an animation.
        animateSwap();
        // ... and start the download.
        Settings.setLastPaidServer(Main.serverAddress);
        downloadFuture = Main.client.downloadFile(downloadingFile, stream);
        final File fDestination = destination;
        // When we're done ...
        downloadFuture.handleAsync((ok, exception) -> {
            // ... swap widgets back out again
            animateSwap();
            if (exception != null) {
                if (!(exception instanceof CancellationException))
                    crashAlert(exception);
            } else {
                // Otherwise inform the user we're finished and let them open the file.
                int secondsTaken = (int) (System.currentTimeMillis() - startTime) / 1000;
                runAlert((stage, controller) -> controller.withOpenFile(stage, downloadingFile, fDestination, secondsTaken));
            }
            return null;
        }, Platform::runLater);
    } catch (InsufficientMoneyException e) {
        if (destination != null)
            destination.delete();
        final String price = Utils.bitcoinValueToFriendlyString(BigInteger.valueOf(selectedFile.get().getPrice()));
        final String missing = String.valueOf(e.missing);
        informationalAlert("Insufficient funds", "This file costs %s BTC but you can't afford that. You need %s satoshis to complete the transaction.", price, missing);
    }
}
Also used : PayFileClient(net.plan99.payfile.client.PayFileClient) Platform(javafx.application.Platform) CancellationException(java.util.concurrent.CancellationException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) DirectoryChooser(javafx.stage.DirectoryChooser)

Example 45 with CancellationException

use of java.util.concurrent.CancellationException in project elasticsearch-jdbc by jprante.

the class JDBCImporter method run.

@Override
public void run() {
    try {
        prepare();
        futures = schedule(settings);
        if (!futures.isEmpty()) {
            logger.debug("waiting for {} futures...", futures.size());
            for (Future future : futures) {
                try {
                    Object o = future.get();
                    logger.debug("got future {}", o);
                } catch (CancellationException e) {
                    logger.warn("schedule canceled");
                } catch (InterruptedException e) {
                    logger.error(e.getMessage());
                } catch (ExecutionException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            logger.debug("futures complete");
        } else {
            execute();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (context != null) {
                context.shutdown();
                context = null;
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

CancellationException (java.util.concurrent.CancellationException)196 ExecutionException (java.util.concurrent.ExecutionException)88 TimeoutException (java.util.concurrent.TimeoutException)50 Test (org.junit.Test)34 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)25 IOException (java.io.IOException)24 CountDownLatch (java.util.concurrent.CountDownLatch)23 Future (java.util.concurrent.Future)23 ArrayList (java.util.ArrayList)18 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)17 Callable (java.util.concurrent.Callable)16 ExecutorService (java.util.concurrent.ExecutorService)13 File (java.io.File)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 List (java.util.List)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 FutureTask (java.util.concurrent.FutureTask)7 Handler (android.os.Handler)6 GwtIncompatible (com.google.common.annotations.GwtIncompatible)6