Collections. synchronizedlist factory Method
Generally, MAP, set, and list implementations are NOT thread-safe. Using these factory methods, you can get the corresponding synchronization container, which is equivalent to enhancing access control. After passing a linked list object, we all perform various operations (both synchronous methods) through the returned linked list object, instead of manipulating the underlying linked list. In addition, the built-in locks are used in the vector and synchronous package classes to support client locks, so we can extend them. You should also pay attention to locking the chain table during iteration. Otherwise, during iteration, if another thread changes the attributes of the container, next, the hasnext method will throw a concurrentmodificationexception (and concurrent containers such as concurrenthashmap do not need to lock the iteration process ). More importantly, to prevent hidden iterations, if you call the tostring Method for a container. The following is the corresponding code.
1. synchronization is required during iteration. List <integer> safelist = collections.
Synchronizedlist(
NewArraylist <integer> ());
Synchronized(Safelist) {iterator <integer> I = safelist. iterator (); // must be in synchronized Block
While(I. hasnext () system.
Out. Println (I. Next ());}
2. Hide the iterator.
Public
ClassHiddeniterator {
Private
FinalSet <integer> set =
NewHashset <integer> ();
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 (); system.
Out. Println ("Debug: added ten elements to" + set); // here }}
2. Implementation of the tostring method in the container.
PublicString tostring () {iterator <E> it = iterator ();
If(! It. hasnext ())
Return"[]";
Stringbuilder sb =
NewStringbuilder (); sb. append ('[');
For(;) {E = it. Next (); sb. append (E =
This? "(This collection)": E );
If(! It. hasnext ())
ReturnSB. append (']'). tostring (); sb. append (','). append ('');}}
Collections. synchronizedlist factory Method