Skip to content
Advertisement

What is a usecase for Java AtomicReference#getAndSet?

What is a usecase for Java AtomicReference#getAndSet? In other words, is it correct assumption, that if the only method from AtomicReference that I use in my code is AtomicReference#getAndSet, then I do not need AtomicReference at all, just a volatile variable would be enough?

For example, if I have the next code:

private final AtomicReference<String> string = new AtomicReference<>("old");

public String getAndSet() {
    return string.getAndSet("new");
}

, isn’t it always doing exactly the same as

private volatile String string = "old";

public String getAndSet() {
    String old = string;
    string = "new";
    return old;
}

from the caller’s point of view?

Advertisement

Answer

No, these are not equivalent. The difference is that getAndSet does both operations atomically, not just an atomic get and then an atomic set.

getAndSet is always guaranteed to return exactly the value that was stored in the reference right before the new value was set. The volatile version might “skip” values inserted by other threads.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement