2

What is the Java equivalent for C# Interlocked.Exchange(Object, Object) : Object? Is there a way in Java to perform the following actions in a single atomic step without lock: 1) store locally the reference of a variable 2) set another reference to the same variable?

jeromerg
  • 2,997
  • 2
  • 26
  • 36

1 Answers1

10

There's no operation to do this for an arbitrary variable, as far as I'm aware... but this is what the AtomicReference type is for:

private AtomicReference<String> stringReference;

...

String oldValue = stringReference.getAndSet(newValue);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194