When you use the Synchronized keyword, the mutex is used to secure threads and synchronize access to shared resources. Threads also often require further coordinated execution to accomplish complex concurrency tasks, such as the wait/notify pattern is a coordinated execution mechanism in a multithreaded environment.
Methods such as obtaining and releasing locks through the API (using mutexes) or calling wait/notify are the means of the underlying invocation. Further, it is necessary to create a higher level of abstraction for thread synchronization. The common use of synchronous helper classes is to further encapsulate the synchronization activity mechanism between 2 or more threads, and its internal principle is to implement complex thread coordination by using the existing underlying API.
There are 5 types of sync helper classes for common synchronization scenarios
1. Semaphore semaphore is a kind of classic synchronization tool. Semaphores are typically used to limit the number of (physical or logical) resources that a thread can access at the same time.
2.CountDownLatch A very simple, but very common, synchronization helper class. The effect is to allow one or more threads to block until a set of operations is performed on another thread.
3.CyclicBarrier A multi-path synchronization point that can be reset, which is useful in some concurrent programming scenarios. It allows a group of threads to wait for each other until they reach a common barrier point (common barrier points). In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier.
4.Phaser A reusable synchronization barrier, functionally similar to Cyclicbarrier and Countdownlatch, but more flexible to use. Ideal for synchronizing a staged compute task in a multithreaded environment (priority use of phaser when synchronizing between subtasks in the Fork/join framework)
5.Exchanger allows two threads to exchange objects at a junction point, which is useful in some piping designs. Exchanger provides a synchronization point at which a pair of threads can exchange data. Each thread provides data to his partner thread through the portal of the Exchange () method, and receives the data provided by his partner thread and returns. When two threads Exchange objects through exchanger, this exchange is safe for two threads. Exchanger can be considered as a bidirectional form of synchronousqueue, which is useful in the application of genetic algorithms and piping design.
I excerpt from: Concurrent Programming Network translation original address translator: He Yixin proofreading: Fang Fei
Five types of synchronization helper classes in Java