1. Synchronizing Container classes
The remaining synchronization container classes include vectors and Hashtable, and the following factory methods are also available in the Java.util.Collections class to create a thread-safe container object:
Collections.synchronizedlist returns a list object that supports synchronous operation (thread safety);
Collections.synchronizedset returns a set object that supports synchronous operation (line Cheng);
Collections.synchronizedmap returns a map object that supports synchronous operation (thread safety);
It is important to note that each individual method in the synchronization container class is thread-safe, but the composite operation of these methods still requires additional client-side locking to protect it. In addition, the synchronization container class object holds a lock during each operation, which results in a much lower throughput. For example:
list<string> synlist = collections.synchronizedlist (list); synchronized (synlist) { for (int i = 0; i < synlist.size ();i++) System.out.println ( Synlist.get (i));}
Calling the size method on the Synlist object and the Get method need to be secured with a client lock, and in this iteration, frequent locking and release locks are required and throughput is low. It is also necessary to use iterators to iterate over the synchronization container class object, or else the concurrentmodificationexception exception will be thrown if another thread is modified during the iteration.
2. Concurrent Container Classes
Concurrent container classes have made significant improvements to the performance of the synchronization container class:
(1) Concurrent container classes provide some common methods of representing composite operations and ensure that these composite operations are thread-safe.
For example: Concurrenthashmap.putifabsent method, equivalent to:
if (!map.contains (key))
Map.put (Key,value);
(2) Concurrent container classes can significantly increase the throughput of operations on concurrent container classes.
(3) The iterator for the concurrent container class is different from the normal iterator, which has weak consistency, does not have a "fast-fail" attribute, and does not throw concurrentmodificationexception.
Common concurrent container classes are:
The concurrentlinkedqueue represents a concurrent queue, and Blockingqueue represents a blocking queue, which increases the number of queued and outbound operations that can be blocked. If the queue is empty, the outbound operation is blocked and, for bounded queues, the queued operation is blocked if the queue is full. Blocking queues can be easily used to implement the "producer-consumer" model.
Copyonwritearraylist represents a parallel, linear table that requires significant overhead by replicating the entire underlying list when each thread makes modifications to the underlying list, which can be very expensive, but is useful for lists that traverse as the primary operation in a multithreaded environment. Copyonwritearrayset is similar to copyonwritelist.
Concurrenthashmap represents a concurrent mapping table, CONCURRENTHASHMAP does not have an exclusive lock like the map of Hashtable and synchronized, and it uses a finer-grained segmentation lock mechanism, which can significantly increase concurrent throughput. However, some methods return results that are inaccurate, such as: the Size method and the IsEmpty method return are not in real-time state. If you need exclusive access to the Map object in a multithreaded environment, you should not use the Concurrenthashmap class.
3. Work-Tight access
In "producer-consumer" mode, producers and consumers share a queue, and in a work-tight situation, each consumer has a double-ended queue that, when the consumer completes his own queue, can go to the end of another consumer queue to work, and not interfere with the work of other consumers. In a work-in-context scenario, the consumer takes his or her job from the team head of his queue and takes someone else's job from the end of the other consumer's team.
Job-taking is well suited to the consumer as well as the producer, and when the consumer executes the job and finds more work to be done, it can be put to the end of his own queue or to the end of the other consumer queue; When the queue does not have work to do, it can go to other consumer queues to get work done, So that every consumer will keep a busy state.
Work-out can be done using deque (double-ended queue), Arraydeque and LinkedList are non-blocking two-ended queue implementations, Blockingdeque represents a blocked double-ended queue, Putfirst, Takefirst, Putlast, Takelast and other methods to achieve blocking access to the team head or tail, Linkedblockingdeque is blocking the implementation of the double-ended queue.
4. Sync Tool Class
The purpose of the synchronization tool class is to coordinate multi-threaded operations according to its own state, which encapsulates states that determine whether certain threads are blocked, and also provides methods for manipulating those states.
Common synchronization tool classes are: Blocking queues, latching, semaphores, fences.
(1) Latching
Latching can delay the progress of a thread until the lockout reaches the terminating state, and it can be used to ensure that certain activities do not continue until one of the other activities is completed. For example:
Ensure that a calculation is performed only after all the resources it needs are ready;
Ensure that a service starts after all the services it relies on are started;
Wait until all participants in an operation are ready;
Countdownlatch is a common implementation of latching, Countdownlatch includes a counter, countdown method to reduce the counter by 1, indicating that an event occurred, the await method causes the calling thread to block until the counter is 0, All events that are waiting for have occurred.
Futuretask can also be used as latching, Futuretask's computational task is implemented by callable, and the callable interface has a call method that can return the results of the calculation. Futuretask provides a Get method that calls the Get method to try to get the results, the task is finished and immediately gets the result, otherwise it will block until the end of the calculation.
(2) Signal volume
Semaphores can be used to control the number of threads concurrently accessing a resource, which can be used to implement a resource pool.
Semaphore is the realization of the semaphore, Semaphore maintains a certain number of licenses, in the execution of operations can be first through the acquire method to obtain a license, if the license has been used up and blocked, after the operation is finished, release the license through the release method.
A semaphore with a number of 1 licenses can act as a mutex and is non-reentrant.
(3) Fence
Fences and lockouts are similar, the main difference being that the fence delays the progress of the thread until all the threads are ready.
Cyclicbarrier is the implementation of the fence, where the thread calls the await method to reach the fence and is blocked if the thread is not the last thread to reach the fence. If the thread is the last thread to reach the fence, it is not blocked and the fence is released and all threads can continue to execute.
Once all the threads are released, the fence is reset and the fence is well suited for parallel iterative algorithms.
Java Concurrent Programming (iii) Common classes in concurrent class libraries