如果你查看StringBuffer
的源代码,你会看到:
/**
* readObject is called to restore the state of the StringBuffer from
* a stream.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
java.io.ObjectOutputStream.PutField fields = s.putFields();
fields.put("value", value);
fields.put("count", count);
fields.put("shared", false);
s.writeFields();
}
/**
* readObject is called to restore the state of the StringBuffer from
* a stream.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
java.io.ObjectInputStream.GetField fields = s.readFields();
value = (char[])fields.get("value", null);
count = fields.get("count", 0);
}
为什么两个不同资源中的两个对象不会不同步?
为什么一个对象不会从两个不同的资源去同步反序列化?
请参阅我的示例:
final ObjectInputStream objectInputABC=new ObjectInputStream(new FileInputStream("ABC"));
final ObjectInputStream objectInputDE=new ObjectInputStream(new FileInputStream("DE"));
final ObjectStreamClass osc = new ObjectStreamClass();
final StringBuffer sb = (StringBuffer) objectInputABC.readObject();
osc.invokeReadObject(sb,objectInputDE);
最佳答案
readObject()
仅在从序列化流构造新对象期间调用。两个线程没有范围在同一个对象上同时执行此方法。
相反,两个线程可能会尝试同时序列化同一个对象,因此 writeObject
是同步的。
关于java - 为什么StringBuffer的readObject不同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27550357/