Java examples for java.util.concurrent.atomic:AtomicReferenceFieldUpdater
Atomically replaces the content of the instance but calls the callback only if the instance holds the terminal value.
/**// w w w . j av a 2s.c om * Copyright 2015 David Karnok and Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ //package com.java2s; import java.util.concurrent.atomic.*; import java.util.function.*; public class Main { /** * Atomically replaces the content of the instance but calls the callback only if the instance holds * the terminal value. * @param updater * @param instance * @param newValue * @param terminalValue * @param onTerminate * @return false if the instance holds the terminal value * @see #set(AtomicReferenceFieldUpdater, Object, Object, Object, Consumer) */ public static <T, U> boolean update( AtomicReferenceFieldUpdater<T, U> updater, T instance, U newValue, U terminalValue, Consumer<? super U> onTerminate) { for (;;) { U a = updater.get(instance); if (a == terminalValue) { if (newValue != null) { onTerminate.accept(newValue); } return false; } if (updater.compareAndSet(instance, a, newValue)) { return true; } } } /** * Atomically replaces the content of the instance but calls the callback only if the instance holds * the terminal value. * @param instance * @param newValue * @param terminalValue * @param onTerminate * @return false if the instance holds the terminal value * @see #set(AtomicReference, Object, Object, Consumer) */ public static <T, U> boolean update(AtomicReference<U> instance, U newValue, U terminalValue, Consumer<? super U> onTerminate) { for (;;) { U a = instance.get(); if (a == terminalValue) { if (newValue != null) { onTerminate.accept(newValue); } return false; } if (instance.compareAndSet(a, newValue)) { return true; } } } }