Project Loom introduces virtual threads to Java, enabling lightweight concurrency. Custom schedulers allow developers to control how these virtual threads are executed, offering flexibility beyond the default ForkJoinPool. This document summarizes the key aspects of custom schedulers in Project Loom.
Purpose of Custom Schedulers
Virtual threads are managed by a scheduler, which maps them to platform threads. The default scheduler, ForkJoinPool, suits most applications but may not meet specific needs, such as prioritizing tasks or integrating with external systems. Custom schedulers let developers define their own scheduling logic to optimize performance or align with application requirements.
Key Ideas
- Scheduler Interface: You write a
Schedulerclass. It needs two methods.schedule(Runnable)queues a task.close()shuts the scheduler down. - Virtual Threads: These are lightweight threads. They run tasks for you. They hand the work to the scheduler.
- Carrier Threads: These are platform threads. They run the virtual thread tasks. The scheduler manages them.
Implementing a Custom Scheduler
To create a custom scheduler, implement the Scheduler interface. For example, a simple scheduler might use a
single-threaded executor:
class SingleThreadScheduler implements Scheduler {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public void schedule(Runnable task) {
executor.submit(task);
}
public void close() {
executor.shutdown();
}
}
More complex schedulers can prioritize tasks, limit concurrency, or integrate with event loops like those in Netty.
Using a Custom Scheduler
To use a custom scheduler, set it when creating a virtual thread:
Scheduler scheduler = new SingleThreadScheduler();
Thread thread = Thread.ofVirtual().scheduler(scheduler).start(runnable);
Alternatively, configure it globally via the jdk.virtualThreadScheduler system property.
Things to Watch For
Tasks can arrive from many threads at once, so the scheduler must handle concurrent submissions safely. Implement close() so it releases every resource the scheduler holds. Bottlenecks in the scheduler's own work matter most in high-throughput applications. Finally, the scheduler should work with Java's existing concurrency tools such as ExecutorService.
Where Custom Schedulers Fit
Custom schedulers shine in three cases. You can bridge virtual threads to legacy systems or event-driven frameworks. You can prioritize critical tasks in real-time applications. You can cap resource use where memory or CPU is tight.
In each case, the scheduler lets you fit virtual threads to the job instead of accepting the default.