ConcurrentModificationException TimerTask

时间:2013-11-29 17:59:19

标签: java arraylist timer timertask concurrentmodification

我在取消第一个计时器后启动第二个计时器时得到ConcurrentModificationException。两个计时器都使用单独的ArrayList并迭代它。没有对列表执行删除/修改,仍然会抛出ConcurrentModificationException

当我停止第一个计时器并立即启动第二个计时器时会发生这种情况。如果我在启动第二个计时器之前等待几秒钟,那么它可以正常工作。

我最终在两个计时器上制作了传入列表的副本,将副本传递给计时器,但我仍然收到错误。不知道为什么我在列表中迭代而只是阅读值。

计时器#1的代码:

private void timerwork(final List<Object> list) throws IOException {
    timer = new Timer();
    final List<Object> taskList = list;
    timer.scheduleAtFixedRate(new CustomTimerTask(taskList) {
        @Override
        public void run() {
            if (taskList != null && !taskList.isEmpty()) {
                synchronized (taskList) {
                    for (Object o: taskList) {
                        try {
                            // this method takes each object, 
                            // does some logic and writes to a flat file, 
                            // it does not modify the object itself, 
                            // but just reads it and does some calculation 
                            // on some local variables
                            valueIncrementOperation(o);
            } catch (IOException e) {
                timer.cancel();
                timer.purge();
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        //once exited out of the loop, it copies the flat file to another file
        try {
            copyFileUsingFileChannels(source, finaldest);
        } catch (IOException ignore) {
        }
    }
}

public synchronized void valueIncrementOperation(Object o) throws IOException {
    DataInputStream d = new DataInputStream(new FileInputStream(sourcefile));
    DataOutputStream out = new DataOutputStream(new FileOutputStream(tempfile));

    initialValue = Long.parseLong(o.getDefaullt_value());
    String count;
    String t;
    while ((count = d.readLine()) != null) {
        String u = count.toUpperCase();
        String[] z = u.split(" ");

        if (z[0].contains(o.getO())) {
            // .............. *snip* ..............
            out.writeBytes(t + "\n");
        }
    d.close();
    out.close();
    copyFileUsingFileChannels(source, initialDest);
}

CustomTimerTask代码:

public class CustomTimerTask extends TimerTask {
    private List<Object> list = new ArrayList<Object>();

    public CustomTimerTask(List<Object> list) {
        this.list = list;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
}

定时器2具有类似的逻辑:即,它在传递给timer2之前复制传入列表。

我仍然收到此错误:

Exception in thread "Timer-0" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

解决方法是在启动timer2之前等待几秒钟。有没有更好的方法来解决这种情况?

1 个答案:

答案 0 :(得分:2)

我们从堆栈跟踪中知道异常是从ArrayList内部抛出的。那么让我们来看看处理List的代码行。 (为便于阅读,删除了多余的代码)

首先是方法调用:

private void timerwork(final List<Object> list) {
    final List<Object> taskList = list;

这意味着taskList 与传入的完全相同的对象(称为list)。

其次,将List传递给CustomTimerTask的构造函数。

timer.scheduleAtFixedRate(new CustomTimerTask(taskList) {

第三,让我们检查一下构造函数:

private List<Object> list = new ArrayList<Object>();
public CustomTimerTask(List<Object> list) {
    this.list = list;
}

因此,您的new ArrayList被删除,并替换为参数list,我们知道该参数与最初传递给timerwork()完全相同的对象

我知道你说过:

  

我最终制作了传入列表的副本

但是在您发布的任何代码中都没有看到这一点。另外,我们不知道(因为你还没有发布)timerwork()的调用代码,但可能只是它是这样的:

List<Object> list = ....
timerwork(list);
timerwork2(list);

如果是这样,那么我们会看到两个计时器任务都在不同线程中的完全相同的对象上运行,这可以解释ConcurrentModificationException

CustomTimerTask的构造函数中,一个简单的修复,即使我的诊断不正确也是一种好的做法:

private List<Object> list;
public CustomTimerTask(List<Object> list) {
    // CustomTimerTask gets its own copy to play with
    this.list = new ArrayList<Object>(list);
}