use of java.util.concurrent.TimeoutException in project guava by google.
the class AbstractFutureTest method testSetFutureCancelBash.
// setFuture and cancel() interact in more complicated ways than the other setters.
public void testSetFutureCancelBash() {
final int size = 50;
final CyclicBarrier barrier = new CyclicBarrier(// for the setter threads
2 + // for the listeners
size + // for the get threads,
size + // for the main thread
1);
final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicReference<AbstractFuture<String>> setFutureFuture = Atomics.newReference();
final AtomicBoolean setFutureSetSucess = new AtomicBoolean();
final AtomicBoolean setFutureCompletionSucess = new AtomicBoolean();
final AtomicBoolean cancellationSucess = new AtomicBoolean();
Runnable cancelRunnable = new Runnable() {
@Override
public void run() {
cancellationSucess.set(currentFuture.get().cancel(true));
awaitUnchecked(barrier);
}
};
Runnable setFutureCompleteSucessFullyRunnable = new Runnable() {
@Override
public void run() {
AbstractFuture<String> future = setFutureFuture.get();
setFutureSetSucess.set(currentFuture.get().setFuture(future));
setFutureCompletionSucess.set(future.set("hello-async-world"));
awaitUnchecked(barrier);
}
};
final Set<Object> finalResults = Collections.synchronizedSet(Sets.newIdentityHashSet());
Runnable collectResultsRunnable = new Runnable() {
@Override
public void run() {
try {
String result = Uninterruptibles.getUninterruptibly(currentFuture.get());
finalResults.add(result);
} catch (ExecutionException e) {
finalResults.add(e.getCause());
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
} finally {
awaitUnchecked(barrier);
}
}
};
Runnable collectResultsTimedGetRunnable = new Runnable() {
@Override
public void run() {
Future<String> future = currentFuture.get();
while (true) {
try {
String result = Uninterruptibles.getUninterruptibly(future, 0, TimeUnit.SECONDS);
finalResults.add(result);
break;
} catch (ExecutionException e) {
finalResults.add(e.getCause());
break;
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
break;
} catch (TimeoutException e) {
// loop
}
}
awaitUnchecked(barrier);
}
};
List<Runnable> allTasks = new ArrayList<Runnable>();
allTasks.add(cancelRunnable);
allTasks.add(setFutureCompleteSucessFullyRunnable);
for (int k = 0; k < size; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
// get usecase and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener = k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
allTasks.add(listener);
allTasks.add(new Runnable() {
@Override
public void run() {
currentFuture.get().addListener(listener, executor);
}
});
}
// sanity check
assertEquals(allTasks.size() + 1, barrier.getParties());
for (int i = 0; i < 1000; i++) {
Collections.shuffle(allTasks);
final AbstractFuture<String> future = new AbstractFuture<String>() {
};
final AbstractFuture<String> setFuture = new AbstractFuture<String>() {
};
currentFuture.set(future);
setFutureFuture.set(setFuture);
for (Runnable task : allTasks) {
executor.execute(task);
}
awaitUnchecked(barrier);
assertThat(future.isDone()).isTrue();
// inspect state and ensure it is correct!
// asserts that all get calling threads received the same value
Object result = Iterables.getOnlyElement(finalResults);
if (result == CancellationException.class) {
assertTrue(future.isCancelled());
assertTrue(cancellationSucess.get());
// 3. after setFuture and set() are called but before the listener completes.
if (!setFutureSetSucess.get() || !setFutureCompletionSucess.get()) {
// If setFuture fails or set on the future fails then it must be because that future was
// cancelled
assertTrue(setFuture.isCancelled());
// we only call cancel(true)
assertTrue(setFuture.wasInterrupted());
}
} else {
// set on the future completed
assertFalse(cancellationSucess.get());
assertTrue(setFutureSetSucess.get());
assertTrue(setFutureCompletionSucess.get());
}
// reset for next iteration
setFutureSetSucess.set(false);
setFutureCompletionSucess.set(false);
cancellationSucess.set(false);
finalResults.clear();
}
executor.shutdown();
}
use of java.util.concurrent.TimeoutException in project guava by google.
the class AbstractScheduledServiceTest method testTimeout.
public void testTimeout() {
// Create a service whose executor will never run its commands
Service service = new AbstractScheduledService() {
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.NANOSECONDS);
}
@Override
protected ScheduledExecutorService executor() {
return TestingExecutors.noOpScheduledExecutor();
}
@Override
protected void runOneIteration() throws Exception {
}
@Override
protected String serviceName() {
return "Foo";
}
};
try {
service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS);
fail("Expected timeout");
} catch (TimeoutException e) {
assertThat(e).hasMessage("Timed out waiting for Foo [STARTING] to reach the RUNNING state.");
}
}
use of java.util.concurrent.TimeoutException in project guava by google.
the class AbstractExecutionThreadServiceTest method testTimeout.
public void testTimeout() {
// Create a service whose executor will never run its commands
Service service = new AbstractExecutionThreadService() {
@Override
protected void run() throws Exception {
}
@Override
protected ScheduledExecutorService executor() {
return TestingExecutors.noOpScheduledExecutor();
}
@Override
protected String serviceName() {
return "Foo";
}
};
try {
service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS);
fail("Expected timeout");
} catch (TimeoutException e) {
assertThat(e).hasMessage("Timed out waiting for Foo [STARTING] to reach the RUNNING state.");
}
}
use of java.util.concurrent.TimeoutException in project rest.li by linkedin.
the class HttpNettyClient method shutdown.
@Override
public void shutdown(final Callback<None> callback) {
LOG.info("Shutdown requested");
if (_state.compareAndSet(State.RUNNING, State.SHUTTING_DOWN)) {
LOG.info("Shutting down");
final long deadline = System.currentTimeMillis() + _shutdownTimeout;
TimeoutCallback<None> closeChannels = new TimeoutCallback<None>(_scheduler, _shutdownTimeout, TimeUnit.MILLISECONDS, new Callback<None>() {
private void finishShutdown() {
_state.set(State.REQUESTS_STOPPING);
// Timeout any waiters which haven't received a Channel yet
for (Callback<Channel> callback : _channelPoolManager.cancelWaiters()) {
callback.onError(new TimeoutException("Operation did not complete before shutdown"));
}
// Timeout any requests still pending response
for (Channel c : _allChannels) {
TransportCallback<RestResponse> callback = c.attr(RAPResponseHandler.CALLBACK_ATTR_KEY).getAndRemove();
if (callback != null) {
errorResponse(callback, new TimeoutException("Operation did not complete before shutdown"));
}
}
// Close all active and idle Channels
final TimeoutRunnable afterClose = new TimeoutRunnable(_scheduler, deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS, new Runnable() {
@Override
public void run() {
_state.set(State.SHUTDOWN);
LOG.info("Shutdown complete");
callback.onSuccess(None.none());
}
}, "Timed out waiting for channels to close, continuing shutdown");
_allChannels.close().addListener(new ChannelGroupFutureListener() {
@Override
public void operationComplete(ChannelGroupFuture channelGroupFuture) throws Exception {
if (!channelGroupFuture.isSuccess()) {
LOG.warn("Failed to close some connections, ignoring");
}
afterClose.run();
}
});
}
@Override
public void onSuccess(None none) {
LOG.info("All connection pools shut down, closing all channels");
finishShutdown();
}
@Override
public void onError(Throwable e) {
LOG.warn("Error shutting down HTTP connection pools, ignoring and continuing shutdown", e);
finishShutdown();
}
}, "Connection pool shutdown timeout exceeded (" + _shutdownTimeout + "ms)");
_channelPoolManager.shutdown(closeChannels);
_jmxManager.onProviderShutdown(_channelPoolManager);
} else {
callback.onError(new IllegalStateException("Shutdown has already been requested."));
}
}
use of java.util.concurrent.TimeoutException in project rest.li by linkedin.
the class TestHttpNettyStreamClient method testNoChannelTimeout.
@Test
public void testNoChannelTimeout() throws InterruptedException {
HttpNettyStreamClient client = new HttpNettyStreamClient(new NoCreations(_scheduler), _scheduler, 500, 500, 1024 * 1024 * 2);
RestRequest r = new RestRequestBuilder(URI.create("http://localhost/")).build();
FutureCallback<StreamResponse> cb = new FutureCallback<StreamResponse>();
TransportCallback<StreamResponse> callback = new TransportCallbackAdapter<StreamResponse>(cb);
client.streamRequest(Messages.toStreamRequest(r), new RequestContext(), new HashMap<String, String>(), callback);
try {
// This timeout needs to be significantly larger than the getTimeout of the netty client;
// we're testing that the client will generate its own timeout
cb.get(30, TimeUnit.SECONDS);
Assert.fail("Get was supposed to time out");
} catch (TimeoutException e) {
// TimeoutException means the timeout for Future.get() elapsed and nothing happened.
// Instead, we are expecting our callback to be invoked before the future timeout
// with a timeout generated by the HttpNettyClient.
Assert.fail("Unexpected TimeoutException, should have been ExecutionException", e);
} catch (ExecutionException e) {
verifyCauseChain(e, RemoteInvocationException.class, TimeoutException.class);
}
}
Aggregations