I use Thread.sleep
when experimenting or demonstrating Java code for concurrency. By sleeping, I am faking some processing work taking place that will take some time.
I wonder about doing this under Project Loom.
- Under Project Loom technology with virtual threads (fibers), can we use
Thread.sleep
in the same way? - Is there any thing different or noteworthy about sleeping a virtual thread versus sleeping a platform/kernel thread?
To educate myself, I have watched some late 2020 videos with Ron Pressler of Oracle presenting Project Loom technology (here, here). While enlightening, I do not recall him addressing the issue of sleeping a thread.
It appears so. I refer to the page on the OpenJDK wiki that addresses blocking operations in Loom. It lists
Thread.sleep()
among operations that are friendly to virtual threads, by which it means thatYou go on to ask,
Documentation is sparse, and it is unclear whether any differences that may actually exist are intentional. Nevertheless, I'm inclined to think that the objective is for sleeping a virtual thread to have semantics as close as possible to those of sleeping an ordinary thread. I suspect that there will be ways for a clever enough program to distinguish, but if there were any differences that rose to the level of "noteworthy" then I expect they would be considered bugs. I base this in part on inference, but I also refer you to the State of Loom document over at java.net, which lists among its "key takeaways" that
and
(Emphasis added.)