为什么StringBuffer的readObject不同步?

时间:2014-12-18 15:41:40

标签: java serialization synchronization

如果您查看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);
}

为什么不能从两个不同的资源中取消同步两个对象?

为什么不会发生一个Object从两个不同的资源反序列化 desynchronized

参见我的例子:

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

1 个答案:

答案 0 :(得分:3)

仅在从序列化流构造新对象期间调用

readObject()。两个线程没有在同一对象上同时执行此方法的范围。

相反,两个线程可能会尝试同时序列化同一个对象,因此writeObject会同步。