As we all know, vector and hashtable are thread-safe in Java. The main reason is that Java has synchronized operations on both, which means locking. Therefore, there will be no problems in the operation of vector and hashtable. But there is a situation: when copying a hashtable to another hashtable, if the flower of the putAll method is used, a java.util.ConcurrentModificationException will be thrown. First upload the code:
TestSync.java
The code copy is as follows:
public class TestSync
{
/**
* main (I use one sentence to describe the function of this method)
* (The applicable conditions for this method are described here)
* @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("iiiiiiiiiii=-------------------" + i);
list.clear();
vec.clear();
//vector and hashtable are thread-safe, and the implementation of the two sets in the putAll method is different
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 copy is as follows:
//synchronized (Constans.USERLIST)
// {
list.putAll(Constans.USERLIST);
// }
When synchronization is not used, an exception is thrown back. It is because Constans.USERLIST is not synchronized, rather than putAll method is not safe.
The difference between Vector and Hashtable is that the Vector's addAll method can run normally without synchronization. This is because the Vector's addAll is different from the Hashtable's putAll method. Vector's addAll will copy the parameters first, so no exception will be generated.
User.java
The code copy is as follows:
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;
}
}
I'm not writing well, everyone forgive me.