Millions
Well, millions if using virtual threads found in Project Loom technology being developed for future versions of Java.
More generally known in the industry as fibers, virtual threads under Project Loom run on top of the "real" platform/kernel threads that we already have in Java. Many virtual threads are mapped to each platform/kernel thread.
The virtual threads provide very cheap blocking. When the task on your background thread does file i/o, network calls, database access, logging, and so on, your code blocks, waiting for a response. Project Loom technology detects this blocking, "parks" (sets aside) that virtual thread, and assigns another virtual thread to continue its work on the platform/kernel thread. This parking and switching is very fast. As a result, threaded Java apps will generally see substantial gains in performance.
As a result, a JVM on mainstream computing hardware will be able to support millions of threads.
Caveats:
- While virtual threads make blocking cheap, those cheap threads may be doing expensive work such as using much memory. So you may need to do some throttling of your tasks in such a case.
- Virtual threads are appropriate for code that involves blocking, which is common in business-oriented apps. However, if the threaded work is CPU-bound such as processing video, then you should use a limited number of "real" platform/kernel threads rather than virtual threads.
Using virtual threads is a easy as switching your implementation of ExecutorService
:
ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor() ;
For more info, see this 2021-01-15 article. And see several very good video presentations and interviews by Ron Pressler and other team members. Study more recent materials as Loom has evolved.
Experimental builds of Project Loom based on early-access Java 18 are available now. The team seeks feedback.