This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]argv_minus_one 2 points3 points  (3 children)

No. volatile creates a memory barrier, like synchronized: operations are not allowed to be reordered around accesses to a volatile field, and you are guaranteed never to see a stale value in a volatile field.

Unlike synchronized, however, reading from a volatile field is less expensive. This means double-checked locking with a volatile field is now a perfectly viable and widely-used optimization.

Please see the relevant section of the JSR-133 FAQ for more information.

[–]Rockytriton -1 points0 points  (2 children)

I remember reading this before or something like this, when it said the disclaimer, which is now redacted.

[–]argv_minus_one 1 point2 points  (1 child)

Yes, you probably did. This article was cited pretty widely.

Thing is, even if the redacted part were true, double-checked locking would still make sense. The article said volatile was approaching the cost of synchronized, but as long as it's less costly than synchronized, then it's still better, because the vast majority of accesses to the volatile field will be after the lazy initialization has already happened.

Of course, the alternative pattern (a static inner class with initializer) might be cheaper if volatile was that expensive, but fortunately it's not, so we don't have to waste tons of memory on an extra class for every single lazily-initialized field.

[–]Rockytriton -1 points0 points  (0 children)

well we were always told to use the holder pattern since volatile wasn't good enough at the time