The synchronization container includes vectors and Hashtable, as well as some factory methods such as Collections.synchronizedxxx.
1, the problem of synchronous container class
Synchronization container classes are thread-safe, but sometimes clients are locked to protect composite operations
Just like the operation of a vector, if two methods one gets the last element of the vector collection, one removes the last element
Then maybe two threads at the same time, the a thread is getting the last element, get (lastelement), and in this process if the B element is being deleted, the last one is deleted and then it may cause a thread execution failure, error
So how do you avoid this problem?
That's it. Gets the index of the last position and gets the data compound operation lock to make it an atomic operation. In the same vein, getting indexes and deletes is also a lock, which takes the container class as the lock object
2. Hidden iterators
As follows
Packagecn.xf.cp.ch05;ImportJava.util.HashSet;ImportJava.util.Random;ImportJava.util.Set; Public classhiddeniterator{Private FinalSet<integer> set =NewHashset<integer>(); //Add and delete operations Public synchronized voidAdd (Integer i) {set.add (i);} Public synchronized voidRemove (Integer i) {set.remove (i);} Public voidaddtenthings () {Random R=NewRandom (); for(inti = 0; I < 10; ++i) {Add (R.nextint ()); } //Note that this may throw an exception because the set is used here, but there is no lock, that is, the object lock that should be added to the Hiddeniterator//in the output log, our set calls the ToString method, which iterates over the container//That is , when the ToString method is called, the set may be modified, and if the counter is modified in the iteration, then Hasnext or next//throws a Concurrentmodificationexception exceptionSystem.out.println ("debug:added ten elements to" +set); }}
Java concurrency Programming Combat 3, synchronization container