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

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

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

SettableFuture.set介绍

[英]Sets the value of this future. This method will return true if the value was successfully set, or false if the future has already been set or cancelled.
[中]设定未来的价值。如果成功设置值,此方法将返回true;如果已设置或取消未来,则此方法将返回false。

代码示例

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

@Override
public synchronized void noMoreLifespans()
{
  checkState(state == State.INITIALIZED || state == State.SPLITS_ADDED);
  noMoreScheduleGroups = true;
  // The listener is waiting for "new lifespan added" because new lifespans would bring new works to scheduler.
  // "No more lifespans" would be of interest to such listeners because it signals that is not going to happen anymore,
  // and the listener should stop waiting.
  whenFinishedOrNewLifespanAdded.set(null);
  whenFinishedOrNewLifespanAdded = SettableFuture.create();
}

代码示例来源: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 testSetFuture_stackOverflow() {
 SettableFuture<String> orig = SettableFuture.create();
 SettableFuture<String> prev = orig;
 for (int i = 0; i < 100000; i++) {
  SettableFuture<String> curr = SettableFuture.create();
  prev.setFuture(curr);
  prev = curr;
 }
 // prev represents the 'innermost' future
 prev.set("done");
 assertTrue(orig.isDone());
}

代码示例来源: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: 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: prestodb/presto

public OutputBufferMemoryManager(long maxBufferedBytes, Supplier<LocalMemoryContext> systemMemoryContextSupplier, Executor notificationExecutor)
{
  requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null");
  checkArgument(maxBufferedBytes > 0, "maxBufferedBytes must be > 0");
  this.maxBufferedBytes = maxBufferedBytes;
  this.systemMemoryContextSupplier = Suppliers.memoize(systemMemoryContextSupplier::get);
  this.notificationExecutor = requireNonNull(notificationExecutor, "notificationExecutor is null");
  bufferBlockedFuture = SettableFuture.create();
  bufferBlockedFuture.set(null);
}

代码示例来源: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 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: prestodb/presto

@Override
public synchronized void startLifespan(Lifespan lifespan, ConnectorPartitionHandle partitionHandle)
{
  checkState(state == State.INITIALIZED || state == State.SPLITS_ADDED);
  scheduleGroups.put(lifespan, new ScheduleGroup(partitionHandle));
  whenFinishedOrNewLifespanAdded.set(null);
  whenFinishedOrNewLifespanAdded = SettableFuture.create();
}

代码示例来源: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: 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: 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: prestodb/presto

private static ListenableFuture<?> firstFinishedFuture(List<ListenableFuture<?>> futures)
{
  if (futures.size() == 1) {
    return futures.get(0);
  }
  SettableFuture<?> result = SettableFuture.create();
  for (ListenableFuture<?> future : futures) {
    future.addListener(() -> result.set(null), directExecutor());
  }
  return result;
}

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

public void testSuccessfulAsList_partialFailure() throws Exception {
 SingleCallListener listener = new SingleCallListener();
 SettableFuture<String> future1 = SettableFuture.create();
 SettableFuture<String> future2 = SettableFuture.create();
 @SuppressWarnings("unchecked") // array is never modified
 ListenableFuture<List<String>> compound = successfulAsList(future1, future2);
 compound.addListener(listener, directExecutor());
 assertFalse(compound.isDone());
 future1.setException(new Throwable("failed1"));
 assertFalse(compound.isDone());
 listener.expectCall();
 future2.set(DATA2);
 assertTrue(listener.wasCalled());
 List<String> results = getDone(compound);
 assertThat(results).containsExactly(null, DATA2).inOrder();
}

代码示例来源: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: prestodb/presto

private ListenableFuture<?> updateDriverBlockedFuture(ListenableFuture<?> sourceBlockedFuture)
{
  // driverBlockedFuture will be completed as soon as the sourceBlockedFuture is completed
  // or any of the operators gets a memory revocation request
  SettableFuture<?> newDriverBlockedFuture = SettableFuture.create();
  driverBlockedFuture.set(newDriverBlockedFuture);
  sourceBlockedFuture.addListener(() -> newDriverBlockedFuture.set(null), directExecutor());
  // it's possible that memory revoking is requested for some operator
  // before we update driverBlockedFuture above and we don't want to miss that
  // notification, so we check to see whether that's the case before returning.
  boolean memoryRevokingRequested = activeOperators.stream()
      .filter(operator -> !revokingOperators.containsKey(operator))
      .map(Operator::getOperatorContext)
      .anyMatch(OperatorContext::isMemoryRevokingRequested);
  if (memoryRevokingRequested) {
    newDriverBlockedFuture.set(null);
  }
  return newDriverBlockedFuture;
}

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

public void testSuccessfulAsList_mixed() throws Exception {
 SingleCallListener listener = new SingleCallListener();
 SettableFuture<String> future1 = SettableFuture.create();
 SettableFuture<String> future2 = SettableFuture.create();
 SettableFuture<String> future3 = SettableFuture.create();
 @SuppressWarnings("unchecked") // array is never modified
 ListenableFuture<List<String>> compound = successfulAsList(future1, future2, future3);
 compound.addListener(listener, directExecutor());
 // First is cancelled, second fails, third succeeds
 assertFalse(compound.isDone());
 future1.cancel(true);
 assertFalse(compound.isDone());
 future2.setException(new Throwable("failed2"));
 assertFalse(compound.isDone());
 listener.expectCall();
 future3.set(DATA3);
 assertTrue(listener.wasCalled());
 List<String> results = getDone(compound);
 assertThat(results).containsExactly(null, null, DATA3).inOrder();
}

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

@Override
public ScheduleResult schedule()
{
  List<RemoteTask> writers = scheduleTasks(getNewTaskCount());
  future.set(null);
  future = SettableFuture.create();
  executor.schedule(() -> future.set(null), 200, MILLISECONDS);
  return new ScheduleResult(done.get(), writers, future, WRITER_SCALING, 0);
}

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

public synchronized ListenableFuture<Supplier<LookupSource>> getLookupSource()
{
  assertState(State.SPILLED);
  unspillingRequested.set(null);
  setState(State.UNSPILLING);
  checkState(unspilledLookupSource == null, "unspilledLookupSource already set");
  unspilledLookupSource = SettableFuture.create();
  return unspilledLookupSource;
}

相关文章