javathread-sleepfibersvirtual-threadsproject-loom

Is `Thread.sleep` different with virtual threads (fibers) in Project Loom for Java


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.

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.


Solution

    • Under Project Loom technology with virtual threads (fibers), can we use Thread.sleep in the same way?

    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 that

    When not pinned, they will release the underlying carrier thread to do other work when the operation blocks.

    You go on to ask,

    • Is there any thing different or noteworthy about sleeping a virtual thread versus sleeping a platform/kernel thread?

    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

    • A virtual thread is a Thread — in code, at runtime, in the debugger and in the profiler.

    and

    • No language changes are needed.

    (Emphasis added.)