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?
Asked
Active
Viewed 1,383 times
2

jeromerg
- 2,997
- 2
- 26
- 36
-
You assume `Interlocked` doesn't use a lock. Any source for that? – Patrick Hofman Sep 23 '16 at 06:59
-
1It doesn't. I will let @jon-skeet answer your question ;-) [Here](http://www.albahari.com/threading/part4.aspx#_Interlocked) you find an detailed explanation. – jeromerg Sep 23 '16 at 07:20
-
Okay. I read from your question you thought it did. – Patrick Hofman Sep 23 '16 at 07:23
1 Answers
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