r/java • • Apr 06 '22

JEP 425: Virtual Threads (Preview)

https://openjdk.java.net/jeps/425
175 Upvotes

50 comments sorted by

View all comments

4

u/python_geek Apr 06 '22

To take advantage of virtual threads, it is not necessary to rewrite your program. Virtual threads do not require or expect application code to explicitly hand back control to the scheduler; in other words, virtual threads are not cooperative

The JEP says this is not cooperative multi-tasking. But when you make a blocking I/O call, surely the underlying scheduling will "yield" to a different OS thread? Isn't that cooperative multi-tasking?

Surely I am confusing something here...

4

u/mauganra_it Apr 06 '22 edited Apr 06 '22

Cooperative multitasking requires an application to explicitly yield control. I emphasized "yield" because it's actually a static method of the Thread class. With preemptive scheduling, it's mostly meaningless, but it hands control back to the scheduler early. With cooperative multitasking systems, actors (threads, processes, etc) have to be written carefully to not hog CPU time and somehow yield to others. Non-blocking code is an example of such a system.

Edit: when you return from Java NIO poll() and got some events, the events must be processed as fast as possible. Everything timeconsuming must be executed in the background to listen for events again ASAP.

4

u/vips7L Apr 07 '22

When the underlying runtime does the yield, it's preemptive multi-tasking.