[concurrency-interest] implementing reentrant locks with Thread.currentThread

Andrew Haley aph at redhat.com
Fri Nov 22 14:04:03 EST 2013


On 11/22/2013 04:11 PM, Sanne Grinovero wrote:
> Hi Andrew,
> that comment was very interesting as it doesn't match with what we
> have observed by sampling on relatively complex applications.
> Could you confirm that it would be similar to a field access even on
> OpenJDK / x86-64 ?

I think so, yes.  r15 is loaded with the address of the thread-local
storage when the VM is entered, so currentThread() generates:

     mov    0x1e0(%r15),%r11

This is most probably super-fast because TLS is in cache.

> Could this be a particularly suited instruction to have the current
> thread de-scheduled? The systems on which I observed this have often
> way too many threads than what I'd like them to have (given the amount
> of real cores), so I expect to always have many threads parked, that
> would affect our sampling information.
> Currently the idea we've got from the diagnostics - by looking at
> sampling only so far - is that we should try avoiding some invocations
> to Thread.currentThread().

That's unlikely IMO.  You can do a little experiment by timing
currentThread() in a loop.  This is hard, because the only way to
prevent HotSpot from optimizing the code away is to use a volatile:

    volatile Thread t;

    void x() {
        t = Thread.currentThread();

and I think you will find that the time will be dominated by the
volatile access, not the call to currentThread().  But please try it.

In the end, if you really want to know what's going on in HotSpot you
have to look at the code that's generated.  I've heard all sorts of
crackpot theories about how to optimize HotSpot that are based on a
completely false idea of how it works.


More information about the Concurrency-interest mailing list