Synchronize block pinning virtual thread – Java

by
Ali Hasan
project-loom

The Problem:

A virtual thread cannot be unmounted during a blocking operation, including executing code inside a synchronized block or method. Why is this the case and how does a semaphore fit into this equation?

The Solutions:

Solution 1: Compare-and-Swap (CAS) vs. Thread Blocking

The difference between synchronized blocks and semaphores lies in their synchronization mechanisms.

Synchronized Blocks:

  • Use a spin lock, which means the thread continues executing instructions while waiting.
  • Block the thread in case of contention.

Semaphores:

  • Use non-blocking CAS (Compare-and-Swap) technique.
  • Yield after a few failed CAS attempts.

Key Distinctions:

  • CAS techniques do not block the thread, whereas synchronized blocks do.
  • ReentrantLock and AQS (which is used by semaphores) also use CAS, but they may still block the thread using LockSupport.park.
  • Virtual Threads cannot be unmounted during blocking operations. Since synchronized blocks block the thread, they require a semaphore to prevent Virtual Thread unmounting.

Q&A

Is a synchronized block a spin lock?

Yes, a synchronized block is implemented as a spin lock in Java.

What is the difference between a synchronized block and a semaphore?

A synchronized block is a non-blocking synchronization primitive, while a semaphore is a blocking synchronization primitive.

Video Explanation:

The following video, titled "Loom is Blooming by José Paumard & Remi Forax - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

These virtual threads can be block at almost no cost. These new ... Java 21 new feature: Virtual Threads #RoadTo21. Java•45K views · 51:52.