Class VirtualThreadFactory
java.lang.Object
express.mvp.myra.transport.VirtualThreadFactory
- All Implemented Interfaces:
ThreadFactory
Thread factory that creates virtual threads with configurable naming and properties.
This factory creates lightweight virtual threads (Project Loom) that are ideal for I/O-bound operations where blocking is acceptable and millions of concurrent tasks need to be handled efficiently.
Virtual Threads vs Platform Threads
| Aspect | Virtual Threads | Platform Threads |
|---|---|---|
| Memory | ~1KB initial stack | ~1MB stack |
| Creation cost | ~1μs | ~1ms |
| Context switch | ~100ns (continuation) | ~10μs (kernel) |
| Max concurrent | Millions | Thousands |
| Blocking impact | Yield to carrier | Block OS thread |
Use Cases
- Callback processing: Handle completion callbacks without blocking I/O thread
- Request handling: One virtual thread per incoming request
- Fan-out operations: Concurrent calls to multiple services
- I/O multiplexing: Wait on multiple channels without selector complexity
Usage Example
VirtualThreadFactory factory = new VirtualThreadFactory("io-worker");
ExecutorService executor = Executors.newThreadPerTaskExecutor(factory);
// Each task runs on its own virtual thread
executor.submit(() -> {
// Blocking is fine - virtual thread yields to carrier
channel.read(buffer);
processData(buffer);
});
Thread Safety
This class is thread-safe. Multiple threads can call newThread(Runnable)
concurrently.
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionVirtualThreadFactory(String namePrefix) Creates a virtual thread factory with the given name prefix.VirtualThreadFactory(String namePrefix, boolean daemon) Creates a virtual thread factory with configurable daemon status. -
Method Summary
-
Constructor Details
-
VirtualThreadFactory
Creates a virtual thread factory with the given name prefix.Created threads will be named "{prefix}-{counter}" and will be daemon threads.
- Parameters:
namePrefix- the prefix for thread names
-
VirtualThreadFactory
Creates a virtual thread factory with configurable daemon status.- Parameters:
namePrefix- the prefix for thread namesdaemon- whether created threads should be daemon threads
-
-
Method Details
-
newThread
Creates a new virtual thread that will execute the given runnable.The thread is not started by this method - the caller must start it.
- Specified by:
newThreadin interfaceThreadFactory- Parameters:
runnable- the task to execute- Returns:
- a new virtual thread (not started)
-
getThreadCount
public long getThreadCount()Returns the number of threads created by this factory.- Returns:
- the total count of threads created
-
getNamePrefix
Returns the name prefix used for thread naming.- Returns:
- the name prefix
-
isDaemon
public boolean isDaemon()Returns whether this factory creates daemon threads.- Returns:
- true if daemon threads are created
-
toString
-