[concurrency-interest] Using a volatile variable as a "guard"

Tim Peierls tim at peierls.net
Mon Feb 7 16:12:53 EST 2011


On Mon, Feb 7, 2011 at 3:45 PM, Joe Bowbeer <joe.bowbeer at gmail.com> wrote:

> So, as a favor to me and others like me, please refrain from using volatile
> if there's a clearer way to do it.
>

Agreed, but there's an important case that I would like to call out:

There are many unsafe classes out there that have public setters primarily
used by reflection-based frameworks to build instances, calling the default
constructor and then the setters. (Tools are better, now, but you still find
the "must have public no-arg constructor" restriction depressingly often.)
As long as clients don't use those setters after an object is published,
things are fine, but there's often no way to guarantee this.

In such cases, I like using volatile on the affected fields, at least as a
first step towards refactoring for safety; it is a simple way to ensure
visibilty and to document what is going on: "Can't make this final -- wish I
could -- best I can do and still be safe." This applies only as long as the
affected fields are independent, but I've seen a *lot* of classes that
qualify. (And in some cases, interdependent fields can be handled with a few
key synchronized blocks.)

If it gets more complicated, with collections being returned and
interdependent state, then the class will need major redesign, but in many
common situations, all you need is volatile.

But otherwise I tend to avoid volatile.

--tim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20110207/65e5ccda/attachment.html>


More information about the Concurrency-interest mailing list