Refine search
@Override public Void call() throws Exception { synchronized (AtmostOneTaskExecutor.this) { // everyone who submits after this should form a next batch inprogress = pending; pending = null; } try { inprogress.set(task.call()); } catch (Throwable t) { LOGGER.log(Level.WARNING, null, t); inprogress.setException(t); } finally { synchronized (AtmostOneTaskExecutor.this) { // if next one is pending, get that scheduled inprogress = null; maybeRun(); } } return null; } });
public void testSetValue_simpleThreaded() throws Exception { SettableFuture<Integer> future = SettableFuture.create(); assertTrue(future.set(42)); // Later attempts to set the future should return false. assertFalse(future.set(23)); assertFalse(future.setException(new Exception("bar"))); assertFalse(future.setFuture(SettableFuture.<Integer>create())); // Check that the future has been set properly. assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertEquals(42, (int) future.get()); }
@Override public void run() { try { exitValue.set(process.waitFor()); } catch (InterruptedException e) { exitValue.setException(e); } } });
public void testSetException() throws Exception { SettableFuture<Object> future = SettableFuture.create(); Exception e = new Exception("foobarbaz"); assertTrue(future.setException(e)); // Later attempts to set the future should return false. assertFalse(future.set(23)); assertFalse(future.setException(new Exception("quux"))); assertFalse(future.setFuture(SettableFuture.create())); // Check that the future has been set properly. assertTrue(future.isDone()); assertFalse(future.isCancelled()); try { future.get(); fail("Expected ExecutionException"); } catch (ExecutionException ee) { assertThat(ee).hasCauseThat().isSameAs(e); } }
public AsyncContext release() { int remaining = latch.decrementAndGet(); if (remaining == 0) { if (exceptions.size() == 0) { future.set(inputs); } else { future.setException(new MultiFailedException(exceptions)); } } throttle.release(); return this; }
public void testSetFuture() throws Exception { SettableFuture<String> future = SettableFuture.create(); SettableFuture<String> nested = SettableFuture.create(); assertTrue(future.setFuture(nested)); // Later attempts to set the future should return false. assertFalse(future.set("x")); assertFalse(future.setException(new Exception("bar"))); assertFalse(future.setFuture(SettableFuture.<String>create())); // Check that the future has been set properly. assertFalse(future.isDone()); assertFalse(future.isCancelled()); try { future.get(0, TimeUnit.MILLISECONDS); fail("Expected TimeoutException"); } catch (TimeoutException expected) { /* expected */ } nested.set("foo"); assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertEquals("foo", future.get()); }
public static <T> ListenableFuture<T> asFuture(CompletionStage<T> stage) { SettableFuture<T> future = SettableFuture.create(); stage.whenComplete((result, throwable) -> { if (throwable != null) { future.setException(throwable); } else { future.set(result); } }); return future; } }
public void testSetFuture_genericsHierarchy() throws Exception { SettableFuture<Foo> future = SettableFuture.create(); SettableFuture<FooChild> nested = SettableFuture.create(); assertTrue(future.setFuture(nested)); // Later attempts to set the future should return false. assertFalse(future.set(new Foo())); assertFalse(future.setException(new Exception("bar"))); assertFalse(future.setFuture(SettableFuture.<Foo>create())); // Check that the future has been set properly. assertFalse(future.isDone()); assertFalse(future.isCancelled()); try { future.get(0, TimeUnit.MILLISECONDS); fail("Expected TimeoutException"); } catch (TimeoutException expected) { /* expected */ } FooChild value = new FooChild(); nested.set(value); assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertSame(value, future.get()); }
public ListenableFuture<WmTezSession> waitForAmRegistryAsync( int timeoutMs, ScheduledExecutorService timeoutPool) { SettableFuture<WmTezSession> future = SettableFuture.create(); synchronized (amPluginInfoLock) { if (amPluginInfo != null) { future.set(this); return future; } if (amRegistryFuture != null) { // We don't need this for now, so do not support it. future.setException(new RuntimeException("Multiple waits are not suported")); return future; } amRegistryFuture = future; if (timeoutMs <= 0) return future; // TODO: replace with withTimeout after we get the relevant guava upgrade. this.timeoutTimer = timeoutPool.schedule( new TimeoutRunnable(), timeoutMs, TimeUnit.MILLISECONDS); } return future; }
@Override public void run() { synchronized (lock) { try { if (!(finished && queue.isEmpty())) { final List<DataSegment> segments = new ArrayList<>(); queue.drainTo(segments); try { announcer.announceSegments(segments); nextAnnoucement = exec.schedule(this, intervalMillis, TimeUnit.MILLISECONDS); } catch (IOException e) { doneAnnouncing.setException( new SegmentLoadingException(e, "Failed to announce segments[%s]", segments) ); } } else { doneAnnouncing.set(true); } } catch (Exception e) { doneAnnouncing.setException(e); } } } },
@Override public void run() { try { started.countDown(); List<ConnectorSplit> batch = getSplits(hiveSplitSource, 1); assertEquals(batch.size(), 1); splits.set(batch.get(0)); } catch (Throwable e) { splits.setException(e); } } });
@Override protected void run() { try { final long exitCode = run0(); result.set(exitCode); } catch (Exception e) { listener.failed(e, getContainerError()); result.setException(e); } }
private void doGetNextBatch() { checkState(splitsProduced <= totalSplits); if (splitsProduced == totalSplits) { switch (atSplitDepletion) { case FAIL: nextBatchFuture.setException(new IllegalStateException("Mock failure")); break; case FINISH: nextBatchFuture.set(ImmutableList.of()); break; case DO_NOTHING: break; default: throw new UnsupportedOperationException(); } } int splits = Math.min(Math.min(batchSize, nextBatchMaxSize), totalSplits - splitsProduced); if (splits != 0) { splitsProduced += splits; nextBatchFuture.set(Collections.nCopies(splits, SPLIT)); } }
@Override public void operationComplete(io.netty.util.concurrent.Future<PushNotificationResponse<SimpleApnsPushNotification>> result) { try { PushNotificationResponse<SimpleApnsPushNotification> response = result.get(); if (response.isAccepted()) { future.set(new ApnResult(ApnResult.Status.SUCCESS, null)); } else if ("Unregistered".equals(response.getRejectionReason())) { future.set(new ApnResult(ApnResult.Status.NO_SUCH_USER, response.getRejectionReason())); } else { logger.warn("Got APN failure: " + response.getRejectionReason()); future.set(new ApnResult(ApnResult.Status.GENERIC_FAILURE, response.getRejectionReason())); } } catch (InterruptedException e) { future.setException(e); } catch (ExecutionException e) { if (e.getCause() instanceof ClientNotConnectedException) setDisconnected(e.getCause()); else future.setException(e.getCause()); } }
private static SettableFuture<State> addTestListener(StateMachine<State> stateMachine) { State initialState = stateMachine.get(); SettableFuture<Boolean> initialStateNotified = SettableFuture.create(); SettableFuture<State> stateChanged = SettableFuture.create(); Thread addingThread = Thread.currentThread(); stateMachine.addStateChangeListener(newState -> { Thread callbackThread = Thread.currentThread(); if (callbackThread == addingThread) { stateChanged.setException(new AssertionError("Listener was not called back on a different thread")); return; } if (newState == initialState) { initialStateNotified.set(true); } else { stateChanged.set(newState); } }); assertTrue(tryGetFutureValue(initialStateNotified, 10, SECONDS).isPresent(), "Initial state notification not fired"); return stateChanged; }
public void testWhenAllSucceed() throws Exception { class PartialResultException extends Exception {} final SettableFuture<Integer> futureInteger = SettableFuture.create(); final SettableFuture<Boolean> futureBoolean = SettableFuture.create(); AsyncCallable<String> combiner = new AsyncCallable<String>() { @Override public ListenableFuture<String> call() throws Exception { throw new AssertionFailedError("AsyncCallable should not have been called."); } }; ListenableFuture<String> futureResult = whenAllSucceed(futureInteger, futureBoolean).callAsync(combiner, directExecutor()); PartialResultException partialResultException = new PartialResultException(); futureInteger.setException(partialResultException); Boolean booleanPartial = true; futureBoolean.set(booleanPartial); try { getDone(futureResult); fail(); } catch (ExecutionException expected) { assertSame(partialResultException, expected.getCause()); } }
protected synchronized void processNodeData(NodeDataMessage msg) { if (requestedNodes == null) { logger.debug("Received NodeDataMessage when requestedNodes == null. Dropping peer " + channel); dropConnection(); } List<Pair<byte[], byte[]>> ret = new ArrayList<>(); if(msg.getDataList().isEmpty()) { String err = String.format("Received NodeDataMessage contains empty node data. Dropping peer %s", channel); logger.debug(err); requestNodesFuture.setException(new RuntimeException(err)); // Not fatal but let us touch it later channel.getChannelManager().disconnect(channel, ReasonCode.TOO_MANY_PEERS); return; } for (Value nodeVal : msg.getDataList()) { byte[] hash = sha3(nodeVal.asBytes()); if (!requestedNodes.contains(hash)) { String err = "Received NodeDataMessage contains non-requested node with hash :" + toHexString(hash) + " . Dropping peer " + channel; dropUselessPeer(err); return; } ret.add(Pair.of(hash, nodeVal.asBytes())); } requestNodesFuture.set(ret); requestedNodes = null; requestNodesFuture = null; processingTime += (System.currentTimeMillis() - lastReqSentTime); lastReqSentTime = 0; peerState = PeerState.IDLE; }
public void testCompletionOrderExceptionThrown() throws Exception { SettableFuture<Long> future1 = SettableFuture.create(); SettableFuture<Long> future2 = SettableFuture.create(); SettableFuture<Long> future3 = SettableFuture.create(); SettableFuture<Long> future4 = SettableFuture.create(); SettableFuture<Long> future5 = SettableFuture.create(); ImmutableList<ListenableFuture<Long>> futures = inCompletionOrder( ImmutableList.<ListenableFuture<Long>>of(future1, future2, future3, future4, future5)); future2.set(1L); future5.setException(new IllegalStateException("2L")); future1.set(3L); future3.set(4L); future4.set(5L); long expectedResult = 1L; for (ListenableFuture<Long> future : futures) { if (expectedResult != 2) { assertEquals((Long) expectedResult, getDone(future)); } else { try { getDone(future); fail(); } catch (ExecutionException expected) { assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("2L"); } } expectedResult++; } }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) { Channel ch = ctx.channel(); if (msg instanceof FullHttpResponse) { FullHttpResponse httpResponse = (FullHttpResponse) msg; final SettableFuture<String> registrationFuture = ch.attr(REGISTRATION_FUTURE).get(); if (httpResponse.headers().contains(UPGRADE, WEBSOCKET, true) && !handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, httpResponse); final String clientRegistrationId = httpResponse.headers().get("X-CLIENT-REGISTRATION-ID"); registrationFuture.set(clientRegistrationId); mockServerLogger.trace("web socket client " + clientRegistrationId + " connected!"); } else if (httpResponse.status().equals(HttpResponseStatus.NOT_IMPLEMENTED)) { String message = readRequestBody(httpResponse); registrationFuture.setException(new WebSocketException(message)); mockServerLogger.warn(message); } else { registrationFuture.setException(new WebSocketException("Unsupported web socket message " + new FullHttpResponseToMockServerResponse().mapMockServerResponseToFullHttpResponse(httpResponse))); } } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { webSocketClient.receivedTextWebSocketFrame((TextWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof CloseWebSocketFrame) { mockServerLogger.trace("web socket client received request to close"); ch.close(); } } }
ready.set( true ); } catch ( Throwable t ) { ready.setException( t );