Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.currentThread().getName() returns empty string "" for Virtual Threads created via Executors.newVirtualThreadPerTaskExecutor()

I am working with Java 19. I have tried to use newly introduced virtual threads as follows:

public static void main(String[] args)  {

    System.out.println("Started with virtual threads");
    try (ExecutorService virtualService = Executors.newVirtualThreadPerTaskExecutor()) {
        virtualService.submit(() -> System.out.println("[" + Thread.currentThread().getName() + "] virtual task 1"));
        virtualService.submit(() -> System.out.println("[" + Thread.currentThread().getName() + "] virtual task 2"));
    }
    System.out.println("Finished");
}

The output of this program is:

Started with virtual threads
[] virtual task 2
[] virtual task 1
Finished

Why Thread.currentThread().getName() does not have any name?

Followup question: How to identify virtual threads between eachother? (how to recognize them) So the output would look like

[thread-1] virtual task 2
[thread-0] virtual task 1
like image 347
fascynacja Avatar asked Dec 05 '25 10:12

fascynacja


1 Answers

tl;dr

long threadId = Thread.currentThread().threadId() ;  // The thread ID is unique and remains unchanged during its lifetime.

Thread name optional

The name of any thread is entirely optional.

You may name a thread if you so desire. This can be handy while debugging. But you should not expect any preset value.

Virtual threads in particular are specified as having no set name. To quote the Javadoc (my emphasis):

Virtual threads do not have a thread name by default. The getName method returns the empty string if a thread name is not set.

Some frameworks, such as JavaFX/OpenJFX, give their threads an informative name.

Thread ID

If you want to identify a Thread, use its ID, a long.

  • In Java 19+, call Thread#threadId.
  • In earlier Java, call Thread#getId

To quote the Javadoc:

Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime.

like image 52
Basil Bourque Avatar answered Dec 06 '25 22:12

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!