Use of synchronized methods in components
Cantor, Scott
cantor.2 at osu.edu
Mon May 5 21:57:24 EDT 2014
One of those "I keep forgetting to mention it" things. I noticed that a
lot of the older components I've done work on used the synchronized
keyword on the setters, but that's not universally true (and I know I've
created some that don't follow that).
My sense is that this is generally wrong for a couple of reasons. One is
that they're by and large prototype beans that won't be shared across
threads, so it's just overhead. That's not 100% true, but it's true in a
lot of the cases (the actions for example).
The other reason is that I think it's a misnomer that it protects the
objects, because the actual work methods post-initialization don't
synchronize on the fields those setters are touching, so I think this is
pointless and dangerous in that it implies safety we don't really have.
My opinion is that the Initializable metaphor is/was basically a
substitute for implicit synchronization in the code, it's a contract
essentially that the objects won't be mutated after initializing them,
guarded by the "throw if initialized" checks in the setters.
Basically, if we're going to synchronize, then we have to do it much more
carefully and widely, in more methods, and in that event we can probably
get rid of Initializeable in those cases. Otherwise, we don't need to do
it at all and should mark them @ThreadSafeAfterInit (that's what I created
it for).
-- Scott
More information about the dev
mailing list