AtomicReference accumulateAndGet Return Values
updateAndGet and accumulateAndGet hand back the new value; getAndUpdate and getAndAccumulate return the old one. All four update atomically.
Code
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;
public class AtomicReturnValues {
public static void main(String[] args) {
AtomicReference<String> state = new AtomicReference<>("v1");
// updateAndGet:应用一元函数,返回【新】值
UnaryOperator<String> bump = cur -> cur + ".1";
System.out.println("updateAndGet: " + state.updateAndGet(bump));
// getAndUpdate:同样原子更新,返回的是【旧】值
System.out.println("getAndUpdate: " + state.getAndUpdate(bump));
System.out.println("now: " + state.get());
// accumulateAndGet:二元函数(current, x),返回【新】值
BinaryOperator<String> append = (cur, x) -> cur + "+" + x;
System.out.println("accumulateAndGet: "
+ state.accumulateAndGet("hotfix", append));
// getAndAccumulate:返回【旧】值
System.out.println("getAndAccumulate: "
+ state.getAndAccumulate("rev2", append));
System.out.println("final: " + state.get());
}
}How it works
Everything happens inside the class AtomicReturnValues and the function main.
Points of care
- The toolchain already provides everything it needs in order to run.
Putting it to use
Entry signature: public static void main(String[] args)
The file’s steps are announced right in the output: updateAndGet:, getAndUpdate:, now:.
The core lines of the flow
AtomicReference<String> state = new AtomicReference<>("v1");
BinaryOperator<String> append = (cur, x) -> cur + "+" + x;
UnaryOperator<String> bump = cur -> cur + ".1";
Interactive Tools for This Topic
FAQ
- What does AtomicReference accumulateAndGet Return Values print when run?
- Running the file directly is enough — expect labeled output lines such as `updateAndGet:`, `getAndUpdate:`, `now:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.