views:

488

answers:

2

May I know what is the difference among lazySet and set method for AtomicInteger. javadoc doesn't talk much about lazySet :

Eventually sets to the given value.

It seems that AtomicInteger will not immediately be set to the desired value, but it will be scheduled to be set in some time. But, what is the practical use of this method? Any example?

+6  A: 

Cited straight from Bug 6275329:

As probably the last little JSR166 follow-up for Mustang, we added a "lazySet" method to the Atomic classes (AtomicInteger, AtomicReference, etc). This is a niche method that is sometimes useful when fine-tuning code using non-blocking data structures. The semantics are that the write is guaranteed not to be re-ordered with any previous write, but may be reordered with subsequent operations (or equivalently, might not be visible to other threads) until some other volatile write or synchronizing action occurs).

The main use case is for nulling out fields of nodes in non-blocking data structures solely for the sake of avoiding long-term garbage retention; it applies when it is harmless if other threads see non-null values for a while, but you'd like to ensure that structures are eventually GCable. In such cases, you can get better performance by avoiding the costs of the null volatile-write. There are a few other use cases along these lines for non-reference-based atomics as well, so the method is supported across all of the AtomicX classes.

For people who like to think of these operations in terms of machine-level barriers on common multiprocessors, lazySet provides a preceeding store-store barrier (which is either a no-op or very cheap on current platforms), but no store-load barrier (which is usually the expensive part of a volatile-write).

yawn
beat me to it lol
amischiefr
By 8 minutes.
Michael Myers
lol yeah, didn't refresh the page before posting :(
amischiefr
Request from Doug Lea :o
Yan Cheng CHEOK
Could someone dumb it down for the rest of us? :(
Gaurav
Lazy is the non-volatile version (e.g. the state change is not guaranteed to be visible to all threads which have the `Atomic*` in scope).
yawn
A: 

Re: attempt to dumb it down -

You can think of this as a way to treat a volatile field as if it wasn't volatile for a particular store (eg: ref = null;) operation.

That isn't perfectly accurate, but it should be enough that you could make a decision between "OK, I really don't care" and "Hmm, let me think about that for a bit".

Paul Mclachlan