0
0
JavaHow-ToBeginner · 4 min read

How to Use Virtual Threads in Java for Lightweight Concurrency

In Java, you can use Thread.startVirtualThread() to create and start a virtual thread, which is a lightweight thread managed by the JVM. Virtual threads allow you to write concurrent code like traditional threads but with much lower resource use and better scalability.
📐

Syntax

To create and start a virtual thread, use Thread.startVirtualThread(Runnable task). This method creates a new virtual thread and immediately starts it. You can also create a Thread object with Thread.ofVirtual().unstarted(Runnable task) and start it later with start().

  • Thread.startVirtualThread(Runnable task): Creates and starts a virtual thread in one step.
  • Thread.ofVirtual().unstarted(Runnable task): Creates a virtual thread but does not start it immediately.
  • start(): Starts a thread that was created but not started.
java
Thread.startVirtualThread(() -> System.out.println("Hello from virtual thread!"));
Output
Hello from virtual thread!
💻

Example

This example shows how to create multiple virtual threads that print messages concurrently. Virtual threads are lightweight, so you can create many without heavy resource use.

java
public class VirtualThreadExample {
    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            System.out.println("Running in virtual thread: " + Thread.currentThread());
        };

        Thread vt1 = Thread.ofVirtual().unstarted(task);
        Thread vt2 = Thread.startVirtualThread(task);

        vt1.start();
        vt2.join();
        vt1.join();
    }
}
Output
Running in virtual thread: Thread[VirtualThread[#1],5,main] Running in virtual thread: Thread[VirtualThread[#2],5,main]
⚠️

Common Pitfalls

One common mistake is confusing virtual threads with platform threads. Virtual threads are lightweight and managed by the JVM, so you should avoid blocking operations that can stall many virtual threads. Also, do not use Thread.sleep() or blocking I/O without understanding how it affects virtual threads.

Another pitfall is forgetting to start a virtual thread created with Thread.ofVirtual().unstarted(). It must be started explicitly with start().

java
/* Wrong: creating but not starting a virtual thread */
Thread vt = Thread.ofVirtual().unstarted(() -> System.out.println("Not started"));
// vt.start(); // Missing start call

/* Right: start the virtual thread */
Thread vtCorrect = Thread.ofVirtual().unstarted(() -> System.out.println("Started"));
vtCorrect.start();
Output
Started
📊

Quick Reference

MethodDescription
Thread.startVirtualThread(Runnable task)Create and start a virtual thread immediately
Thread.ofVirtual().unstarted(Runnable task)Create a virtual thread without starting it
start()Start a thread created but not started
Thread.currentThread()Get the current thread (virtual or platform)
Virtual threadsLightweight threads managed by JVM for scalable concurrency

Key Takeaways

Use Thread.startVirtualThread() to quickly create and run virtual threads.
Virtual threads are lightweight and allow many concurrent tasks with low overhead.
Always start virtual threads created with Thread.ofVirtual().unstarted() using start().
Avoid blocking operations that can stall virtual threads and reduce scalability.
Virtual threads simplify concurrent programming with familiar Thread APIs.