When you use the synchronized keyword, a mutex is used to ensure thread safety and synchronous access to shared resources. Further coordinated execution between threads is often required to complete complex concurrent tasks. For example, the wait/notify mode is a coordinated execution mechanism in a multi-threaded environment.
Acquiring and releasing locks through the API (using a mutex) or calling wait/notify and other methods are all low-level calling methods. Further, it is necessary to create a higher level abstraction for thread synchronization. The commonly used synchronization auxiliary class is to further encapsulate the synchronization activity mechanism between two or more threads. Its internal principle is to achieve complex coordination between threads by using the existing underlying API.
There are 5 synchronization helper classes suitable for common synchronization scenarios:
1. Semaphore Semaphore is a classic synchronization tool. Semaphores are often used to limit the number of resources (physical or logical) that a thread can access simultaneously.
2.CountDownLatch is a very simple but commonly used synchronization auxiliary class. Its purpose is to allow one or more threads to block until a set of operations being performed in other threads is completed.
3. CyclicBarrier is a resettable multi-way synchronization point that is useful in certain concurrent programming scenarios. It allows a group of threads to wait for each other until a common barrier point is reached. CyclicBarrier is useful in programs involving a set of fixed-size threads that must wait for each other from time to time. Because the barrier can be reused after the waiting thread is released, it is called a cyclic barrier.
4. Phaser is a reusable synchronization barrier that is similar in function to CyclicBarrier and CountDownLatch, but is more flexible in use. It is very suitable for synchronously coordinating phased computing tasks in a multi-threaded environment (when synchronization is required between subtasks in the Fork/Join framework, Phaser is preferred)
5.Exchanger allows two threads to exchange objects at a certain meeting point, which is more useful in certain pipeline designs. Exchanger provides a synchronization point at which a pair of threads can exchange data. Each thread provides data to its partner thread through the entry of the exchange() method, and receives the data provided by its partner thread and returns it. When two threads exchange objects through Exchanger, the exchange is safe for both threads. Exchanger can be considered as a bidirectional form of SynchronousQueue, which is more useful in applications involving genetic algorithms and pipeline design.