A lightweight thread is a Thread
David Lloyd
david.lloyd at redhat.com
Wed Oct 23 12:49:46 UTC 2019
On Wed, Oct 23, 2019 at 3:59 AM Andrew Haley <aph at redhat.com> wrote:
>
> On 10/22/19 5:27 PM, David Lloyd wrote:
> > One would still have to allow subclassing of threads though IMO, even
> > in the lightweight case. This is enormously useful
>
> What is it about subclassing Thread that is enormously useful? I can't
> immediately think of any case where a scoped local couldn't achieve the
> same thing. Instead of
>
> (MyFoo)Thread.current();
>
> you'd have
>
> CurrentFoo.get();
>
> ... which would work in lightweight and heavyweight Threads. Is there
> something that definitely wouldn't work with this mechanism?
Apart from being the fastest possible way to have thread local values
in Java, there are a couple things we can only do by subclassing
Thread. In JBoss EAP and WildFly, we support custom interrupt
handlers (this is something that is in the JDK but is not public, thus
subclassing Thread is the only way to do it) and interrupt deferral
(only Thread subclasses can do this). Vert.x/Netty uses a custom
thread subclass to support "faster" thread locals (though looking at
the code I suspect these "faster" thread locals might be heavier than
the JDK's thread local support).
Sometimes you want to be able to do `ThreadSubclass foo =
notCurrentThread(); foo.something();`. From what I understand, one
can't easily get a scoped local for some other thread.
We also use it for user-supplied thread shutdown hooks, but of course
that can also be done by wrapping the Runnable (via ThreadFactory for
instance).
I did a search in my IDE's Quarkus code base and in the JDK and
supporting projects, there are presently 374 Thread subclasses. I'm
not sure what percentage of those really *needs* to be an actual
subclass though. Most of the JDK cases (based on a random sampling)
appear to just override the `run()` method and probably carry over (at
least stylewise) from a very old JDK.
A project called "zkclient" is also handling thread interruption, so I
guess we're not the only ones. Maybe it's worth making that API be
public.
--
- DML
More information about the loom-dev
mailing list