CountDownLatch, Semaphore four major concurrent Tools Detailed

Java Concurrency Kit

file

1. Concurrent Tools

Provides more advanced than the synchronized synchronization of various structures: including CountDownLatch, CyclicBarrier, Semaphore, etc., can achieve a richer multi-threaded operation.

2. concurrent containers

Offers a variety of thread-safe container: The most common ConcurrentHashMap, orderly ConcurrentSkipListMap, to achieve dynamic arrays thread safe CopyOnWriteArrayList and so on.

3. concurrent queue

To achieve a variety of BlockingQueue: common ArrayBlockingQueue, SynchorousQueue or PriorityBlockingQueue for a specific scene.

4.Executor framework

You can create a variety of different types of thread pools, scheduled tasks such as running, in most cases, no longer need to re-implement their own thread pools and task scheduler.

file

Java common concurrent containers

1.ConcurrentHashMap

Concurrent containers are often used, the JDK underlying data structures 1.7 and 1.8 has changed (follow-up article will explain), there may be recommendations learning sequence is as follows: From the Java7 HashMap -> Java7 ConcurrentHashMap -> Java8 HashMap -> Java8 ConcurrentHashMap, so may be more good grasp this concurrent containers, after all, evolved from the HashMap.

2.ConcurrentSkipListMap

Care about the order, data needs to be very frequent changes

3.CopyOnWrite container

CopyOnWrite container that is copy-on-write vessel. From the beginning JDK1.5 Java concurrency package provides two mechanisms to achieve concurrent use CopyOnWrite container, CopyOnWriteArrayList and CopyOnWriteArraySet.

4. Concurrent queue of various

The various BlockedQueue achieved, typical ArrayBlockingQueue, SynchorousQueue.

For more details see: the principle of concurrent container, seven concurrent Detailed container, and usage scenarios

file

Java Concurrency commonly used tools

file

1.CountDownLatch

1) Function

CountDownLatch auxiliary class is a synchronous, allowing one or more threads, a set of waiting for other threads to finish, and then continue.

2) Principle:

  • CountDownLatch is achieved by a counter, the initial counter value of the required number of waiting threads.
    file
  • The main thread calls await CountDownLatch () method blocks the current thread (ie: the main thread waits on the lockout) until the counter is 0.
  • When a worker thread completed its task, calling CountDownLatch of countDown () value method, the counter will be decremented by one.
  • When the counter value is 0, indicating that all the worker threads are executed over, this time on the waiting locking the main thread can resume execution tasks.

3) application scenarios

Countdown Timer

For example: A typical scenario is that a rocket launch. Before the rocket launch, in order to ensure foolproof, often we have to check the equipment, instruments. Only after the completion of all the checks and so on, the engine can ignite. This scenario is very suitable for use CountDownLatch.

It can make ignition threads, waiting threads fully completed after all the checks, then execute

4) use

static final CountDownLatch end = new CountDownLatch(10);end.countDown();end.await();

5) a schematic view:

file

2.CyclicBarrier

1) Function:

CyclicBarrier literally means can be reused (Cyclic) barrier (Barrier). It needs to be done is to let a group of threads reach a barrier (also called synchronization point) is blocked when it until the last thread reaches the barrier, the barrier will open the door, all barriers blocked thread will continue to run.

And CountDownLatch similar, is waiting for some threads are done at a later time.

2) the difference between CountDownLatch

This counter that can be used repeatedly. For example, suppose we will counter is set to 10. Then cobble together the first 10 threads, counter is zero, then the next and then cobble together a group of 10 threads.

3) Principle

1) CyclicBarrier is implemented by a counter, the initial counter value of the required number of waiting threads. eg: CyclicBarrier c = new CyclicBarrier (2); // number of waiting threads 2

2) Each thread calls CyclicBarrier the await () method to make themselves into a wait state.

3) When all threads are called CyclicBarrier after the await () method, all threads stop waiting, continue to run.

4) use

public CyclicBarrier (int parties, Runnable barrierAction) await barrierAction operation is completed when the timer one count, the system will execute ()

5) a schematic view:

file

3. Semaphore Semaphore

1) Function: the Java provides an implementation of the classic semaphores Semaphore, which is by permit (permit) controls a number of ways to achieve the purpose of restricting access to common resources. For example: control the number of concurrent threads.

2) Principle:

1) Semaphore is implemented by a counter (the number of records of the license), the initial counter value of the required number of waiting threads.

file

2) by a thread acquire () method to get a license (counter value minus 1), only to get a license before they can continue execution, or blocks the current thread.

3) Thread () method to return the license (counter value plus 1) release.

Note: Use tryAcquire () method can immediately get the result: Try to get a license, if the acquisition is successful, then immediately returns true, if the acquisition fails, it immediately returns false.

3) application scenarios:

Semaphore can be used to do traffic control, in particular, with limited public resources application scenarios, such as database connection.

For a scene: for example, in railway stations, airports and other taxi, when a lot of empty taxis in place to prevent overcrowding, dispatchers command waiting car of a team come in five people on the train, and other five people on a bus, came alive again next batch. This works Semaphore is somewhat similar.

4. Exchanger exchanger

1) Function: Exchanger (exchanger) is a tool for inter-thread class collaboration. Exchanger for exchanging data between threads. It provides a synchronization point, in this synchronization point two threads may exchange data with each other. These two threads to exchange data exchange method, if the first thread to execute exchange method, it would have been to wait for a second thread also performs exchange, when two threads have reached the synchronization point, these two threads can exchange data , this thread will be produced by the data is passed to the other side.

2) Principle:

A thread calls the public V exchange (V dataA) method, thread A synchronizing point is reached, and waits until the synchronization point reaches the front thread B.

Thread B calls public V exchange (V dataB) method, the thread B reaches the synchronization point.

When thread A and thread B has reached the synchronization point, the thread will own the data is passed to the other side, the two threads of the completion of the exchange of data.

3) Exchanger application scenarios

Exchanger can be used for a scene proofreading work.

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin juejin.im/post/5df24bef518825126874c2e9