project-loomjava-19

How to know which platform thread is carrying the virtual thread?


Is there a way to know which platform thread is carrying the current virtual thread or pin a virtual thread to a platform thread and get its threadlocal in JDK19? I want to reuse some objects in virtual threads, something like sync.Pool in Golang.


Solution

  • From JEP 425, the spec for virtual threads in JDK 19:

    The identity of the carrier is unavailable to the virtual thread.

    So, no, I don't think there is any way to determine which platform thread is running a virtual thread (i.e. in Java code; there are ways to observe this via tooling such as the Java Flight Recorder).

    Pinning a thread is something to be avoided [1], and so I doubt there is any way to explicitly do that. From the same JEP 425:

    a running virtual thread is logically independent of its current carrier

    Given the above quote, and various presentations/documentation to that effect, I would be very surprised if there were a way to pin a thread explicitly via an API.

    Finally, regarding ThreadLocals, there is a discussion at [2] where the Project Loom team mentions the dangers of caching expensive objects in ThreadLocals (note that they do not mention access to the underlying platform thread). I'm not familiar with the Go construct but you may want to consider JEP 429 on Extent-Locals.

    [1] - see 36m20s here, a presentation by the Project Loom team

    [2] - see 35m01s here, the same presentation by the Project Loom team