.Thread.currentThread().getName() is "" for a virtual thread
Alan Bateman
Alan.Bateman at oracle.com
Tue May 17 10:44:41 UTC 2022
On 17/05/2022 10:25, Lutz Horn wrote:
> Hi,
>
> using non-virutal threads, `Thread.currentThread().getName()` can be
> used to get the name of the current thread. This has a sensible value
> for threads managed by, for example, a
> `Executors.newFixedThreadPool(256)`.
>
> Calling `.getName()` on a virtual thread managed by a
> `Executors.newVirtualThreadPerTaskExecutor()` returns the empty string
> "".
>
> Doing without `.getName()` in this szenario,
> `Thread.currentThread().toString()` returns something like
>
> "VirtualThread[#96]/runnable at ForkJoinPool-1-worker-3"
>
> which is fine but a little long for use cases such as logging.
>
> What is the recommended way to get a short string representation of a
> virtual thread?
>
Unlike platform threads, virtual threads are specified to not get an
automatically generated name by default. The String representation has
the thread identifier (#96 in this case) and its state. Maybe the thread
identifier is enough for what you are doing? Note that you can provide
your own ThreadFactory that names threads if you want.
-Alan.
More information about the loom-dev
mailing list