4 ms·
There is an example in TFA which shows how if you have a normal thread pool and two tasks with one sleeping indefinitely and only a single thread to execute, th
by gleenn 4y ago
There is an example in TFA which shows how if you have a normal thread pool and two tasks with one sleeping indefinitely and only a single thread to execute, the the second thread never executes. Then the example switches to virtual threads and both can execute (after also adding a sleep). This shows how you can have more tasks than threads and everything still can get a chance to run. That's not true with Futures prior to this. M:N means you can run more tasks in parallel than you have threads, just not with a speedup or more parallelism. So only virtual threads are M:N.
- riku_iki 4y agoI think what you are describing is API for manual scheduling: you call sleep() to give up control to scheduler. With tasks/futures you supposed to submit another task to pool which will wake up after certain time. Both are "green threads" with manual scheduler (you need to make explicit call to give up control to scheduler) but different API.
- erpellan 4y agoThread.sleep on a platform thread takes that thread out of action until the sleep ends. If an executor with 10 threads got 10 tasks that all called Thread.sleep(1000000) then it can run no more tasks until one of the threads wakes up. When a virtual thread sleeps or blocks on IO it is unhooked from the underlying platform thread so another virtual thread can run. You can have an almost unlimited number of virtual threads multiplexed over a small number of carrier (platform) threads. Hence M:N
- riku_iki 4y agoIn your view advancement is that in "green threads" they overloaded Thread.sleep(..), so it doesn't call real Thread.sleep() but doing something like Futures + ExecutionService underneath instead. Java already had tons of non-blocking io/http and many other frameworks without "green threads" but using futures and executionservice. Green threads look like syntactic sugar.
- Phelinofist 4y agoI think Thread.yield() would do that?
- xxs 4y agoThread.yield() is very weird, and something I'd not advise using aside spin lock with backoff. It's OS dependent, and if may just bounce to the OS and back, continuing the current execution.