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
long threadId = Thread.currentThread().threadId() ; // The thread ID is unique and remains unchanged during its lifetime.
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.
If you want to identify a Thread, use its ID, a long.
Thread#threadId.Thread#getIdTo quote the Javadoc:
Returns the identifier of this
Thread. The thread ID is a positivelongnumber generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With