ANdroid序列化导致ConcurrentModificationException.我该如何避免这种情况



在序列化我的对象时,我的对象是一个自定义类,包含各种ArrayLists,每隔一段时间就会出现并发Mod异常。很明显,一个或多个数组主义者正在抛出这个。但我不知道在哪里,也不知道如何修复它。实现迭代器是我的第一个想法,但如何进行序列化呢?

这是我的序列化代码:enter code here

 try{
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    try { 
          ObjectOutput out = new ObjectOutputStream(bos); 
          out.writeObject(TGame);
          // Get the bytes of the serialized object 
          byte[] buf = bos.toByteArray(); 
          File sdCard = Environment.getExternalStorageDirectory();
          File dir = new File (sdCard.getAbsolutePath() + "/game_folder");
          dir.mkdirs();
          File file = new File(dir, "serializationtest");

          FileOutputStream fos = new FileOutputStream(file);
              //this.openFileOutput(filename, Context.MODE_PRIVATE);
          fos.write(buf);
          fos.close(); 
        } catch(IOException ioe) { 
          Log.e("serializeObject", "error", ioe); 

        }catch(StackOverflowError e){
            //do something
        }
        File f =this.getDir(filename, 0);
        Log.v("FILE SAVED",f.getName());    
    }catch(ConcurrentModificationException e){
        //do something          
    }
}

当Java api序列化对象(此处为内部数组列表)时,如果同时有其他线程对ArrayList进行结构修改,则会出现并发Mod异常。

一种解决方案是锁定机制,确保一次只有一个线程访问该对象。另一个简单的解决方案是,要编写的对象创建该对象的浅层副本并序列化该副本。这样,即使原始的ArrayList发生了更改,浅层复制也不会起作用,并且可以正常工作。例如

class Test {
 int a;
 string b;
 ArrayList<String> c;
 Test(Test t){
  this.a=t.a;
  this.b=t.b;
  this.c=new ArrayList<String>(t.c);
 }
}
FileOutputStream fos = new FileOutputStream(file);
//write a copy of original object
      fos.write(new Test(t));
}

相关内容

最新更新