Introduction to five synchronization helper classes in Java

  • 2020-04-01 03:16:27
  • OfStack

  When you use the synchronized keyword, you use the mutex to ensure thread safety and synchronized access to Shared resources. There is also often a need for more coordinated execution between threads to complete complex concurrent tasks, such as the wait/notify pattern, which is a coordinated execution mechanism in multi-threaded environments.

Methods such as acquiring and releasing locks through the API (using the mutex) or calling wait/notify are the underlying calls. Further, it is necessary to create a higher level of abstraction for thread synchronization. The common synchronization helper 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 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 assist class. Its effect is to allow one or more threads to remain blocked until a set of operations is completed in another thread.

CyclicBarrier is a resettable multiplex synchronization point that is useful in some concurrent programming scenarios. It allows a group of threads to wait with each other until they reach a common barrier point. CyclicBarrier is useful in a program involving a fixed set of threads that must wait on each other from time to time. Because the barrier can be reused after releasing the waiting thread, it is called the barrier of the loop.

A reusable synchronization barrier similar in function to CyclicBarrier and CountDownLatch, but more flexible in use. It is ideal for synchronously coordinating phased computing tasks in a multi-threaded environment (Phaser is preferred when synchronization is required between subtasks in the Fork/Join framework)

5. Exchanger allowing two threads in a meeting to exchange object, is useful when certain pipeline design. Exchanger provides a synchronization point, in the synchronous point, a thread can exchange data. Each thread provides data to its partner thread through the entry of the exchange() method, receives the data provided by its partner thread, and returns it. When two threads through the Exchanger exchanged objects, the exchange for two threads are safe. Exchanger can be thought of as the two-way SynchronousQueue will form in the applied to the genetic algorithm and the application of the pipeline design is useful.


Related articles: