1, Thread-safe hashmap
If a thread-safe hashmap is required, it can be implemented using the Synchronizedmap (map<k,v> m) method of the Collection tool class.
Collections.synchronizedmap (m);
Into the method,
Public static <K,V> map<k,v> synchronizedmap (map<k,v> m) { returnNew synchronizedmap<k,v>(m); }
It returns an inner class that goes into the inner class
Private Static class Synchronizedmap<k,v> implements map<k,v>, Serializable { private Final Map<k,v> m; // backing Map Final Object Mutex;
}
Found that it is implemented using the proxy method, all functions are transmitted in the map, that is, m implementation, it is only responsible for the method lock. Such as:
Public v put (K key, V value) { synchronized(mutex) {return m.put (key, value);} } Public V get (Object key) { synchronized(mutex) {return m.get (key);} }
In addition to this method, there are more professional concurrenthashmap, can be found in the original blog related content.
2. Thread-Safe List
Similar to HashMap, a thread-safe ArrayList or LinkedList can also be obtained by collections.synchronizedlist (list).
Similarly, the JDK provides a copyonwritearraylist for thread safety.
Copyonwritearraylist is suitable for reading and writing less scenes, for him to read the operation does not need to lock, read and write occurs at the same time will not be blocked, as long as the writing occurs at the same time only need to synchronize.
During a write operation, it replicates once, then modifies it on the copied copy, and finally replaces the original data with the copy.
3. Data sharing channel: Blockingqueue
It is an interface that is commonly used to share data between threads, with the following specific implementations:
Here's how it's used:
Where, when you put, the end of the team to press a data, such as the queue is full, then wait for the queue to go in, when you take, if it is empty, you will wait until it is not empty.
Java High concurrency Programming (vii) concurrent containers for--JDK