Re: Why "lock" functionality is introduced for all the objects?
On Tue, 28 Jun 2011, Alex J wrote:
I'm curious why Java designers once decided to allow every object to be
lockable (i.e. allow using lock on those). I know, that out of such a
design decision every Java object contain lock index, i.e. new Object()
results in allocation of at least 8 bytes where 4 bytes is object index
and 4 bytes is lock index on 32- bit JVM.
That's not quite right. In the olden days, it's true that every object
header contained room for a lock pointer - but back then, that meant that
every header was *three* words (12 bytes), not two. Two words were needed
for the header (one for a vtable pointer, one for various other things),
and the third was for the lock.
What happened then was that a very clever chap called David Bacon, who
worked for IBM, invented a thing called a thin lock:
http://www.research.ibm.com/people/d/dfb/papers.html#Bacon98Thin
Which was subsequently improved by another clever chap called Tamiya
Onodera into a thing called a tasuki lock, which you don't hear so much
about.
The details are described quite clearly in the papers, but the upshot is
that an object is created with neither a lock nor a slot for a lock
pointer (and so only a two-word header), and the lock is allocated only
when needed, and then wired in. Some fancy footwork means that the object
doesn't need to grow a pointer when this happens; the header remains two
words, at the expense of some slight awkwardness elsewhere. Some even
fancier footwork means that if only one thread locks the object at a time
(a very common pattern), then a lock doesn't even need to be allocated.
The better decision, IMHO, would be to introduce lock/wait mechanics for
only, say, the Lockable descendants.
I agree with this, actually. There might be some small performance
improvement, but it would also make the locking behaviour of code more
explicit, and so clearer.
tom
--
Why did one straw break the camel's back? Here's the secret: the million
other straws underneath it - it's all mathematics. -- Mos Def