pekko
pekko copied to clipboard
Virtual Thread Support: replace synchronized with ReentrantGuard
Motivation:
As there is onging work to make VT works well with monitor,not sure when , maybe in JDK 25, but we can do better to remove some synchronized block.
According to https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-04C03FFC-066D-4857-85B9-E5A27A875AF9:
A current limitation of the implementation of virtual threads is that performing a blocking operation while inside a synchronized block or method causes the JDK's virtual thread scheduler to block a precious OS thread, whereas it wouldn't if the blocking operation were done outside of a synchronized block or method. We call that situation "pinning".
Pekko already has org.apache.pekko.util.ReentrantGuard (extends Java's ReentrantLock) which has a withGuard function.
val lock = new ReentrantGuard()
def fun(): T = {
lock.withGuard {
// ... function body returning an instance of T
}
}
ReentrantGuard.withGuard calls ReentrantLock lock() and waits until the lock is available and when it completes (successfully or not), it calls ReentrantLock unlock().
Running the JVM with -Djdk.tracePinnedThread=full is a useful way to be notified about pinned threads.
I think this should be a discussion. I think we have 1 open already. An issue needs a reasonably concrete set of steps. Lazy Val's used synchronization under the hood. So finding a non synchronized alternative is a good place to start.
refs: https://github.com/vavr-io/vavr/issues/2760 , yes I just found this.
@He-Pin can we rework this issue to focus on replacing the use of this.synchronized with ReentrantLocks? That is a more achievable issue than 'Virtual thread friendly'. Someone would be more inclined to contribute the ReentrantLock solution.
@pjfanning YES, PLEASE.
Hi @He-Pin , I would be happy to contribute. Please let me know this issue can be assigned to me if not picked up by someone already?
@KrnSaurabh I don't think we want this change at the moment. ReentrantGuards are slower than synchronized blocks.
@KrnSaurabh In JDK25, this is been fixed, so I think we can just drop this.
https://openjdk.org/jeps/8337395 JEP draft: Adapt Object Monitors for Virtual Threads