Java Code Examples for java.util.concurrent.atomic.AtomicReference#updateAndGet()

The following examples show how to use java.util.concurrent.atomic.AtomicReference#updateAndGet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RouterUtils.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Atomically replace the exception for an operation depending on the precedence of the new exception.
 * First, if the current operationException is null, directly set operationException as exception;
 * Second, if operationException exists, compare ErrorCodes of exception and existing operation Exception depending
 * on precedence level. An ErrorCode with a smaller precedence level overrides an ErrorCode with a larger precedence
 * level. Update the operationException if necessary.
 * @param operationExceptionRef the {@link AtomicReference} to the operation exception to potentially replace.
 * @param exception the new {@link RouterException} to set if it the precedence level is lower than that of the
 *                  current exception.
 * @param precedenceLevelFn a function that translates a {@link RouterErrorCode} into an integer precedence level,
 *                          where lower values signify greater precedence.
 */
static void replaceOperationException(AtomicReference<Exception> operationExceptionRef, RouterException exception,
    ToIntFunction<RouterErrorCode> precedenceLevelFn) {
  operationExceptionRef.updateAndGet(currentException -> {
    Exception newException;
    if (currentException == null) {
      newException = exception;
    } else {
      int currentPrecedence = precedenceLevelFn.applyAsInt(
          currentException instanceof RouterException ? ((RouterException) currentException).getErrorCode()
              : RouterErrorCode.UnexpectedInternalError);
      newException =
          precedenceLevelFn.applyAsInt(exception.getErrorCode()) < currentPrecedence ? exception : currentException;
    }
    return newException;
  });
}
 
Example 2
Source File: AsyncPacketProvider.java    From andesite-node with MIT License 5 votes vote down vote up
AsyncPacketProvider(IPacketProvider packetProvider, int backlog, AtomicReference<Future<?>> taskRef) {
    this.packetProvider = packetProvider;
    this.queue = new ArrayBlockingQueue<>(backlog);
    
    taskRef.updateAndGet(__ -> CommonAsync.WORKER_POOL.submit(new ProvideForkJoinTask(
            () -> this.packetProvider.getNextPacketRaw(this.talking.get()),
            this.queue
    )));
}
 
Example 3
Source File: Suppliers.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * It generates a cached version of the supplier. The delegate supplier is only called once
 * regardless of how may the client calls get().
 *
 * @param delegate the delegate
 * @param <T> the type of the supplier response.
 * @return a cached version of the supplier.
 */
public static <T> Supplier<T> memoize(Supplier<T> delegate) {
    AtomicReference<T> value = new AtomicReference<>();
    return () -> {
        T val = value.get();
        if (val == null) {
            val = value.updateAndGet(cur -> cur == null ?
                Objects.requireNonNull(delegate.get()) : cur);
        }
        return val;
    };
}
 
Example 4
Source File: Util.java    From hollow with Apache License 2.0 5 votes vote down vote up
static <T> Supplier<T> memoize(Supplier<T> supplier) {
    AtomicReference<T> value = new AtomicReference<>();
    return () -> {
        T val = value.get();
        if (val == null)
            val = value.updateAndGet(v -> v == null ? requireNonNull(supplier.get()) : v);
        return val;
    };
}
 
Example 5
Source File: StrategyProvider.java    From robozonky with Apache License 2.0 5 votes vote down vote up
private static <T> T set(final AtomicReference<T> ref, final Supplier<Optional<T>> provider, final String desc) {
    final T value = ref.updateAndGet(old -> provider.get()
        .orElse(null));
    if (Objects.isNull(value)) {
        LOGGER.info("{} strategy inactive or missing, disabling all such operations.", desc);
    } else {
        LOGGER.debug("{} strategy correctly loaded.", desc);
    }
    return value;
}
 
Example 6
Source File: TestStreamProcessor.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamProcessorWithStreamProcessorListenerFactory() {
  AtomicReference<MockStreamProcessorLifecycleListener> mockListener = new AtomicReference<>();
  StreamProcessor streamProcessor =
      new StreamProcessor("TestProcessorId", mock(Config.class), new HashMap<>(), mock(TaskFactory.class),
          Optional.empty(), Optional.empty(), Optional.empty(), sp ->
          mockListener.updateAndGet(old -> new MockStreamProcessorLifecycleListener(sp)),
          mock(JobCoordinator.class), Mockito.mock(MetadataStore.class));
  assertEquals(streamProcessor, mockListener.get().processor);
}
 
Example 7
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
private <T> T updateAndGet(AtomicReference<T> ref, T current) {
  final T updated = ref.updateAndGet(previous -> previous != null? previous: current);
  Preconditions.assertTrue(updated == current, "previous != null");
  LOG.info("{}: start {}", id, current.getClass().getSimpleName());
  return updated;
}
 
Example 8
Source File: RoleInfo.java    From ratis with Apache License 2.0 4 votes vote down vote up
private <T> T updateAndGet(AtomicReference<T> ref, T current) {
  final T updated = ref.updateAndGet(previous -> previous != null? previous: current);
  Preconditions.assertTrue(updated == current, "previous != null");
  LOG.info("{}: start {}", id, current.getClass().getSimpleName());
  return updated;
}
 
Example 9
Source File: ConcurrencyUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @return defaultValue if the reference contains null (in that case defaultValue is placed there), or reference value otherwise.
 */
@Nonnull
public static <T> T cacheOrGet(@Nonnull AtomicReference<T> ref, @Nonnull T defaultValue) {
  return ref.updateAndGet(prev -> prev == null ? defaultValue : prev);
}