Search in sources :

Example 21 with CancellationException

use of java.util.concurrent.CancellationException in project Hystrix by Netflix.

the class HystrixCommandTest method testCancelFutureWithInterruptionWhenPropertySaysNotTo.

@Test
public void testCancelFutureWithInterruptionWhenPropertySaysNotTo() throws InterruptedException, ExecutionException {
    // given
    InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true, false, 1000);
    // when
    Future<Boolean> f = cmd.queue();
    Thread.sleep(500);
    f.cancel(true);
    Thread.sleep(500);
    // then
    try {
        f.get();
        fail("Should have thrown a CancellationException");
    } catch (CancellationException e) {
        assertFalse(cmd.hasBeenInterrupted());
    }
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) CancellationException(java.util.concurrent.CancellationException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 22 with CancellationException

use of java.util.concurrent.CancellationException in project jersey by jersey.

the class JettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback callback) {
    final Request jettyRequest = translateRequest(jerseyRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest);
    final ContentProvider entity = getStreamProvider(jerseyRequest);
    if (entity != null) {
        jettyRequest.content(entity);
    }
    final AtomicBoolean callbackInvoked = new AtomicBoolean(false);
    final Throwable failure;
    try {
        final CompletableFuture<ClientResponse> responseFuture = new CompletableFuture<ClientResponse>().whenComplete((clientResponse, throwable) -> {
            if (throwable != null && throwable instanceof CancellationException) {
                // take care of future cancellation
                jettyRequest.abort(throwable);
            }
        });
        final AtomicReference<ClientResponse> jerseyResponse = new AtomicReference<>();
        final ByteBufferInputStream entityStream = new ByteBufferInputStream();
        jettyRequest.send(new Response.Listener.Adapter() {

            @Override
            public void onHeaders(final Response jettyResponse) {
                HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), JettyConnector.this.getClass().getName());
                if (responseFuture.isDone()) {
                    if (!callbackInvoked.compareAndSet(false, true)) {
                        return;
                    }
                }
                final ClientResponse response = translateResponse(jerseyRequest, jettyResponse, entityStream);
                jerseyResponse.set(response);
                callback.response(response);
            }

            @Override
            public void onContent(final Response jettyResponse, final ByteBuffer content) {
                try {
                    entityStream.put(content);
                } catch (final InterruptedException ex) {
                    final ProcessingException pe = new ProcessingException(ex);
                    entityStream.closeQueue(pe);
                    // try to complete the future with an exception
                    responseFuture.completeExceptionally(pe);
                    Thread.currentThread().interrupt();
                }
            }

            @Override
            public void onComplete(final Result result) {
                entityStream.closeQueue();
                // try to complete the future with the response only once truly done
                responseFuture.complete(jerseyResponse.get());
            }

            @Override
            public void onFailure(final Response response, final Throwable t) {
                entityStream.closeQueue(t);
                // try to complete the future with an exception
                responseFuture.completeExceptionally(t);
                if (callbackInvoked.compareAndSet(false, true)) {
                    callback.failure(t);
                }
            }
        });
        processContent(jerseyRequest, entity);
        return responseFuture;
    } catch (final Throwable t) {
        failure = t;
    }
    if (callbackInvoked.compareAndSet(false, true)) {
        callback.failure(failure);
    }
    CompletableFuture<Object> future = new CompletableFuture<>();
    future.completeExceptionally(failure);
    return future;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) OutputStreamContentProvider(org.eclipse.jetty.client.util.OutputStreamContentProvider) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) Request(org.eclipse.jetty.client.api.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) ByteBufferInputStream(org.glassfish.jersey.internal.util.collection.ByteBufferInputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) Result(org.eclipse.jetty.client.api.Result) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(org.eclipse.jetty.client.api.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) CancellationException(java.util.concurrent.CancellationException) ProcessingException(javax.ws.rs.ProcessingException)

Example 23 with CancellationException

use of java.util.concurrent.CancellationException in project failsafe by jhalterman.

the class FailsafeFuture method cancel.

/**
   * Attempts to cancel this execution. This attempt will fail if the execution has already completed, has already been
   * cancelled, or could not be cancelled for some other reason. If successful, and this execution has not started when
   * {@code cancel} is called, this execution should never run. If the execution has already started, then the
   * {@code mayInterruptIfRunning} parameter determines whether the thread executing this task should be interrupted in
   * an attempt to stop the execution.
   *
   * <p>
   * After this method returns, subsequent calls to {@link #isDone} will always return {@code true}. Subsequent calls to
   * {@link #isCancelled} will always return {@code true} if this method returned {@code true}.
   *
   * @param mayInterruptIfRunning {@code true} if the thread executing this execution should be interrupted; otherwise,
   *          in-progress executions are allowed to complete
   * @return {@code false} if the execution could not be cancelled, typically because it has already completed normally;
   *         {@code true} otherwise
   */
@Override
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
    if (done)
        return false;
    boolean cancelResult = delegate.cancel(mayInterruptIfRunning);
    failure = new CancellationException();
    cancelled = true;
    config.handleComplete(null, failure, execution, false);
    complete(null, failure, config.fallback, false);
    return cancelResult;
}
Also used : CancellationException(java.util.concurrent.CancellationException)

Example 24 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 25 with CancellationException

use of java.util.concurrent.CancellationException in project hs4j by killme2008.

the class FutureImpl method get.

/**
	 * {@inheritDoc}
	 */
public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    long startTime = System.currentTimeMillis();
    long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, unit);
    synchronized (this.sync) {
        for (; ; ) {
            if (this.isDone) {
                if (this.isCancelled) {
                    throw new CancellationException();
                } else if (this.failure != null) {
                    throw new ExecutionException(this.failure);
                } else if (this.result != null) {
                    return this.result;
                }
            } else if (System.currentTimeMillis() - startTime > timeoutMillis) {
                throw new TimeoutException();
            }
            this.sync.wait(timeoutMillis);
        }
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

CancellationException (java.util.concurrent.CancellationException)178 ExecutionException (java.util.concurrent.ExecutionException)84 TimeoutException (java.util.concurrent.TimeoutException)49 Test (org.junit.Test)28 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)25 IOException (java.io.IOException)24 CountDownLatch (java.util.concurrent.CountDownLatch)22 Future (java.util.concurrent.Future)22 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 Callable (java.util.concurrent.Callable)15 ArrayList (java.util.ArrayList)14 ExecutorService (java.util.concurrent.ExecutorService)13 File (java.io.File)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 FutureTask (java.util.concurrent.FutureTask)7 Handler (android.os.Handler)6 GwtIncompatible (com.google.common.annotations.GwtIncompatible)6 AccessibleObject (java.lang.reflect.AccessibleObject)6 List (java.util.List)6