Thread.getState() very slow

David Holmes David.Holmes at
Sun Jul 11 04:09:47 UTC 2010

Hi Doug,

Doug Lea said the following on 07/10/10 23:35:
> I've been trying out some improvements in ForkJoin
> that involve repeatedly scanning threads to check
> whether they are still in state Thread.State.RUNNABLE.

My question is why you want to check for Runnable? Is this a heuristic 
check to see that the thread is not blocked? Only basic monitor related 
blocking will update the thread state. Is that enough for what you want?

Not to mention the inherent race in doing the check.

> This is shockingly slow because getState() is implemented
> using a lookup table that requires a global lock
> (to ensure initialization) plus boxing to do the lookup.

We can easily fix the lock issue with a DCL check and making the main 
map volatile. (Or simply skip lazy initialization as I would think this 
is always used!)

Is the boxing really an issue? Due to the values used there should not 
be any object creation - right?

That said the set of states is small enough that two arrays could easily 
be used instead of the maps.

> Practically any other implementation would be faster.
> For example, simply scanning the small static array of 
> sun.misc.VM.getThreadStateValues. And surely there are
> better ways.
> Is anyone looking into this?

I don't see any CRs related to this so I would not expect anyone to be 
looking at it ... until now of course :)

> Or alternatively, is there a faster way to check that
> internal field Thread.threadStatus has the value mapping

Can you use Unsafe to grab the field directly, or would the reflection 
make it too slow?


> If not, I might try contributing a patch.
> -Doug

More information about the core-libs-dev mailing list