ConcurrentModificationException错误

时间:2016-01-22 15:45:31

标签: java multithreading concurrentmodification

我发生了ConcurrentModificationException错误;这是引用:

at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at org.eclipse.om2m.IOTproject.ipu.Monitor.start(Monitor.java:31)
at org.eclipse.om2m.IOTproject.ipu.Activator$1$1.run(Activator.java:39)

这里是Monitor类中的线程开始:

public void start() throws Exception {
    ServerUDP server = new ServerUDP();
    Thread t = new Thread(server);
    t.start();

    while (true) {
        Iterator<Pacchetto> it = server.A.iterator();

        while (it.hasNext()) {
            Pacchetto o = (Pacchetto) it.next();
            Utils.insertResource(o);

此类调用ServerUDP类中的线程

public void run() {
    Controllore c = new Controllore(A);
    c.start();
    DatagramSocket serverSocket = null;
    try {
        serverSocket = new DatagramSocket(4445);
        //TODO chiudi pacchetto
    } catch (SocketException e1) {
        e1.printStackTrace();
    }
    byte[] receiveData = new byte[1024]; 
    while(true){
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        try {
            serverSocket.receive(receivePacket);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String msg = new String(receivePacket.getData());    
        Date date = new Date();
        Pacchetto o = new Pacchetto();

            o.setIP(msg);
            o.setTimestamp(date);

            Iterator<Pacchetto> iterator1 = A.iterator();
            boolean flag = true;
            while (iterator1.hasNext()) {
                Pacchetto obj = (Pacchetto) iterator1.next();
                if (obj.getIP().equals(o.getIP())) {
                    obj.setTimestamp(o.getTimestamp());
                    flag = false;
                    break;
                }
            }

            if (flag) {
                System.out.println("Added " + o.getIP());
                A.add(o);
            }

            System.out.println("Check -------------");
            for (int i=0; i< A.size() ; i++)
            {
                System.out.println(A.get(i).getIP());       
            }
            }
    }
}

Pacchetto是一个由我定义的对象。我该如何解决这个问题?感谢

1 个答案:

答案 0 :(得分:0)

这里看起来问题是你的列表server.A可能不是线程安全的。由于此列表可能同时被多个线程访问,因此我们最好能够安全地进行并发访问。

我们需要做一些事情来使这个列表线程安全。

  1. 让我们使列表A同步。这可以作为

    完成
    List A = Collections.synchronizedList(new ArrayList());
    
  2. 我们应该确保此列表中的所有迭代都是通过 synchronized块中的迭代器执行的,并且列表中获取了锁。

    synchronised (A) {
        Iterator iterator1 = A.iterator(); // Must be in synchronized block
        while (iterator1.hasNext())
        Pacchetto obj = (Pacchetto) iterator1.next();
    }