Search code examples
javac#lockinginterlocked

What is the Java equivalent for C# `Interlocked.Exchange(Object, Object) : Object`?


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?


Solution

  • 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);