下面列出了java.util.concurrent.atomic.AtomicReference#updateAndGet() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
});
}
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
)));
}
/**
* 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;
};
}
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;
};
}
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;
}
@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);
}
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;
}
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;
}
/**
* @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);
}