As we all know, the vector and Hashtable in Java are thread-safe, mainly Java has added synchronized to both operations, that is, locked. Therefore, the operation of vectors and Hashtable is not problematic. But there is a situation: When a Hashtable copy to another Hashtable, if the use of Putall method of flowers, will throw a java.util.ConcurrentModificationException exception. First code:
Testsync.java
The code is as follows |
Copy Code |
public class Testsync {
/** * Main (the function of this method is described here in one sentence) * (Here is a description of the method applicable conditions-optional) * @param args * @return void * @exception * @since 1.0.0 */ public static void Main (string[] args) { map<integer,user> list = new Hashtable<integer, user> (); list<user> VEC = new vector<user> (); Testthread thread = new Testthread (); Thread.Start (); int i = 0; while (i<1000) { i++; System.out.println ("iiiiiiiiii=------------" + i); List.clear (); Vec.clear ();
Vectors and hashtable are thread-safe, and two sets of Putall methods do not implement the same Vec.addall (Constans.uservec); Synchronized (constans.userlist) // { List.putall (constans.userlist); // } System.out.println ("--------" + list.size ()); System.out.println ("--------" + vec.size ()); } System.out.println ("over---------------------------------------------"); }
}
Class Constans { public static map<integer,user> userlist = new Hashtable<integer, user> (); public static list<user> Uservec = new vector<user> (); }
Class Testthread extends Thread { @Override public void Run () { for (int i=0;i<100000;i++) { User user = new user (); User.setid (i); User.setname ("name" + i); if (! Constans.USERLIST.containsKey (i)) { Constans.USERLIST.put (I,user); Constans.USERVEC.add (user); }
} SYSTEM.OUT.PRINTLN ("Thread End------------"); }
} |
When we will
The code is as follows |
Copy Code |
Synchronized (constans.userlist) // { List.putall (constans.userlist); // } |
When synchronization is not used, the exception is thrown back. is because constans.userlist is not a step, not a Putall method is unsafe.
The vector and Hashtable are different from the vector AddAll method does not use synchronization can also function normally, that is because the vector AddAll and Hashtable Putall method is different, Vector addall will copy the parameters first, so no exception will be generated.
The code is as follows |
Copy Code |
User.java public class User { private int id; private String name; public int getId () { return ID; } public void setId (int id) { This.id = ID; } Public String GetName () { return name; } public void SetName (String name) { THIS.name = name; }
} |
The writing is not good, everybody forgives.