[JAVA concurrent programming practice] 3. Synchronization container and java practice
The synchronization containers include Vector and Hashtable, and some are created by factory methods such as Collections. synchronizedXxx.
1. Synchronization container Problems
Synchronization containers are thread-safe, but sometimes the client needs to be locked to protect compound operations.
For example, if another two methods are used to obtain the last element of a vector set and delete the last element
When two threads operate simultaneously, thread A is first obtaining the last element, get (lastElement). If Element B is being deleted during this process, after the last (last) is deleted, the execution of thread A may fail and an error is returned.
So how can we avoid this problem?
That is to say, to obtain the index at the last position and to obtain the data composite operation and lock it into an atomic operation. Similarly, obtaining indexes and deleting indexes are also locking the container class as the Lock Object.
2. Hide the iterator
As follows:
Package cn. xf. cp. ch05; import java. util. hashSet; import java. util. random; import java. util. set; public class HiddenIterator {private final Set <Integer> set = new HashSet <Integer> (); // add and delete public synchronized void add (Integer I) {set. add (I);} public synchronized void remove (Integer I) {set. remove (I);} public void addTenThings () {Random r = new Random (); for (int I = 0; I <10; ++ I) {add (r. nextInt ();} // note that an exception may be thrown here because set is used but no lock is applied, that is, the HiddenIterator object lock should be added before it can be // while output logs, our set will call the toString method, this method will iterate on the container // that is, the set may be modified when the toString method is called, if the counter is modified during iteration, hasNext or next // will throw a ConcurrentModificationException System. out. println ("DEBUG: added ten elements to" + set );}}