Shirgill Farhan Ansari Shirgill Farhan Ansari - 1 year ago 77
Java Question

If a variable is modified to reference a different AtomicLong, will the update be visible then?

If I am doing something like this in a class-

private AtomicLong count = new AtomicLong(0);

and then inside a method, I do this-

count = new AtomicLong(1); // will this update is going to be visible to other threads

I am confused because

Answer Source

You're completely missing the point of AtomicLong.

AtomicLong provides methods to manipulate it in a thread-safe manner.
Replacing your instance with a new instance bypasses all of those.

You should make all AtomicLong variables final to prevent that.

You also need to make sure that you don't try to read the same value twice, because other threads could change it between your reads. See my blog post for more on thread-safe code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download