pekko icon indicating copy to clipboard operation
pekko copied to clipboard

Virtual Thread Support: replace synchronized with ReentrantGuard

Open He-Pin opened this issue 1 year ago • 4 comments

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.

He-Pin avatar Jan 31 '24 16:01 He-Pin

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.

pjfanning avatar Jan 31 '24 16:01 pjfanning

refs: https://github.com/vavr-io/vavr/issues/2760 , yes I just found this.

He-Pin avatar Jan 31 '24 17:01 He-Pin

@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 avatar Feb 01 '24 11:02 pjfanning

@pjfanning YES, PLEASE.

He-Pin avatar Feb 01 '24 11:02 He-Pin

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 avatar Sep 23 '24 16:09 KrnSaurabh

@KrnSaurabh I don't think we want this change at the moment. ReentrantGuards are slower than synchronized blocks.

pjfanning avatar Sep 23 '24 17:09 pjfanning

@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

He-Pin avatar Sep 24 '24 03:09 He-Pin