Synchronous and concurrent usage analysis in Java

  • 2020-04-01 03:55:35
  • OfStack

This article analyzes the use of synchronization and concurrency in Java in more detail. Share with you for your reference. Specific analysis is as follows:

1. The synchronous container class consists of two parts: vector and hashtable

Another kind is synchronized wrapper classes, by the Collections synchronizedXXX created. The synchronization container provides serial access to all the state of the container for thread safety.

They have the following problems:

A) additional lock protection is required for conforming operations. For example, iteration, missing, add and so on conditional operation.
B) toString, hashCode, equals are all called iteratively indirectly, and concurrency should be paid attention to.
 
2. Concurrent containers in java5.0.

ConcurrentHashMap can replace the synchronous Map implementation.

CopyOnWriteArrayList is a synchronous implementation of a List when it is primarily a read operation.
Meanwhile, Queue and BlockingQueue: ConcurentLinkedQueue: FIFO Queue were added.
PriorityQueue: a non-concurrent priority order queue.
BlockingQueue adds blocking inserts and fetters.

A) ConcurentHashMap: instead of using a common lock, separate locks are used. Any number of reader threads can access the map concurrently, readers and writers can access the map concurrently, and a limited number of writes can concurrently modify the map. However, the size and isEmpty languages are reduced to estimates.

B) CopyOnWriteArrayList: the iterator keeps a reference to the underlying array, and the reference will not be changed.
 
3. The Synchronizer

A) CountDownLatch. After the constructor parameter is n and n is 0 through countDown, all await threads continue execution.

B) FutureTask: calculate a Runnable implemented by Callable that can carry results. Include: wait, run and complete.

C) Semaphore: controls the number of activities that can be accessed simultaneously

D) CyclicBarrier: similar to blocking. Locks wait for events, levels wait for other threads. Initial n, Runnable r, n threads await (), when n threads finish executing and reach the level, r executes, the level is reset, and n threads continue.

I hope this article has been helpful to your Java programming.


Related articles: