com.google.common.util.concurrent.SettableFuture.setException()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(137)

本文整理了Java中com.google.common.util.concurrent.SettableFuture.setException()方法的一些代码示例,展示了SettableFuture.setException()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SettableFuture.setException()方法的具体详情如下:
包路径:com.google.common.util.concurrent.SettableFuture
类名称:SettableFuture
方法名:setException

SettableFuture.setException介绍

[英]Sets the future to having failed with the given exception. This exception will be wrapped in an ExecutionException and thrown from the get methods. This method will return true if the exception was successfully set, or false if the future has already been set or cancelled.
[中]将未来设置为在给定异常情况下失败。此异常将被包装在ExecutionException中,并从get方法中抛出。如果成功设置了异常,则此方法将返回true;如果已设置或取消了未来,则此方法将返回false。

代码示例

代码示例来源:origin: jenkinsci/jenkins

@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;
  }
});

代码示例来源:origin: google/guava

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());
}

代码示例来源:origin: googleapis/google-cloud-java

@Override
 public void run() {
  try {
   exitValue.set(process.waitFor());
  } catch (InterruptedException e) {
   exitValue.setException(e);
  }
 }
});

代码示例来源:origin: google/guava

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);
 }
}

代码示例来源:origin: apache/storm

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;
}

代码示例来源:origin: google/guava

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());
}

代码示例来源:origin: spotify/apollo

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;
 }
}

代码示例来源:origin: google/guava

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());
}

代码示例来源:origin: apache/hive

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;
}

代码示例来源:origin: apache/incubator-druid

@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);
   }
  }
 }
},

代码示例来源:origin: prestodb/presto

@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);
    }
  }
});

代码示例来源:origin: spotify/helios

@Override
protected void run() {
 try {
  final long exitCode = run0();
  result.set(exitCode);
 } catch (Exception e) {
  listener.failed(e, getContainerError());
  result.setException(e);
 }
}

代码示例来源:origin: prestodb/presto

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));
  }
}

代码示例来源:origin: signalapp/Signal-Server

@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());
 }
}

代码示例来源:origin: prestodb/presto

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;
}

代码示例来源:origin: google/guava

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());
 }
}

代码示例来源:origin: ethereum/ethereumj

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;
}

代码示例来源:origin: google/guava

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++;
 }
}

代码示例来源:origin: jamesdbloom/mockserver

@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();
    }
  }
}

代码示例来源:origin: pentaho/pentaho-kettle

ready.set( true );
} catch ( Throwable t ) {
 ready.setException( t );

相关文章