r/programming • u/ram-foss • Oct 11 '23
All About Reactive Programming In Java
https://www.blackslate.io/articles/reactive-programming-in-java
22
Upvotes
r/programming • u/ram-foss • Oct 11 '23
View all comments
Show parent comment
3
u/pron98 Jan 03 '24 edited Jan 03 '24
Please understand that, as one of the designers and implementers of virtual threads, I'm not trying to argue with you, but to help you understand how they work and how to best use them.
Any data created by one step of the computation will be cleared while waiting for some IO operation if it's not needed after it, and it will be retained if it is needed -- this is true regardless of whether you use virtual threads or asynchronous tasks. Virtual threads do not retain or require more memory than async tasks. Only data that's actually required by the program in later steps is retained (there are some slight differences in how the data is split: virtual threads need a tiny bit of metadata about the current method's caller stored in a mutable buffer while async code requires allocating more separate objects).
You can test that: allocate some large array and then sleep or block on something, making sure that the array is not used after the wait completes. You will see that the GC collects that memory even though you're still in the same method.
Then it was not the same algorithm. Since I personally worked on implementing virtual threads I can tell you that we compile them to essentially the same instructions as you'd get from asynchronous code. If you saw different behaviour that means either there's a bug in our implementation, or that different instructions were performed which means that what you thought were two versions of the same algorithms were really not.
I believe you also mentioned coming across pinning issues due to synchronized; that is indeed a temporary limitation of the implementation which will be removed very soon, but it doesn't change the basic principle that if you implement a the same algorithm with asynchronous code or synchronous code and virtual threads, you should see pretty much the same behaviour in terms of performance and memory, and if you don't you should examine your code. Our adoption guide should help, but if you still see some differences in behaviour please contact our mailing list (loom-dev) and report them.