A detailed description of the vector and hashtable operations in java. The vector and hashtable are thread-safe, mainly because java adds synchronized to both operations, if you need to know these two functions, please come in and have a look.
As we all know, in java, vector and hashtable are thread-safe, mainly because java adds synchronized to both operations, that is, locking. Therefore, the operations on vector and hashtable are normal. However, when a hashtable is copied to another hashtable, if the putAll method is used, a java. util. ConcurrentModificationException exception is thrown. First run the Code:
TestSync. java
The Code is as follows: |
Copy code |
Public class TestSync { /** * Main (Here we use a sentence to describe the role of this method) * (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 ();
// Vector and hashtable are thread-safe. The two sets of putAll are implemented differently. 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 ended ------------"); }
} |
When we
The Code is as follows: |
Copy code |
// Synchronized (Constans. USERLIST) //{ List. putAll (Constans. USERLIST ); //} |
If synchronization is not used, an exception is thrown back. Because Constans. USERLIST is not synchronized, The putAll method is not safe.
The difference between Vector and Hashtable is that the addAll method of Vector can run normally without synchronization, because the addAll method of Vector is different from that of Hashtable, addAll of Vector will copy the parameter first, so no exception will occur.
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; }
} |
Sorry.