【问题标题】:ANdroid Serialization causes ConcurrentModificationException. How can I avoid this?AAndroid 序列化导致 ConcurrentModificationException。我怎样才能避免这种情况?
【发布时间】:2011-06-02 13:30:32
【问题描述】:

在序列化我的对象时,它是一个自定义类,包含各种 ArrayList,我经常遇到并发 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          
    }
}

【问题讨论】:

  • 你为什么要捕获 StackOverflowException?
  • @sudocode:这可以防止问题被否决。 ;)
  • @Mikaveli - 想不出更好的理由来抓住它。 8-)
  • Z为什么要抓 StackOverflow?我不知道。我正在为这个问题而烦恼,并且序列化也导致了 Stacoverflws,所以我把它放进去看看会发生什么挫折。我把它留在了那里,因为它似乎没有造成任何伤害。

标签: java android serialization synchronization concurrentmodification


【解决方案1】:

当 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));

}

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多