0

我们知道,新的 JMM 保证不会看到部分构造的对象或其最终字段的多个值。http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.2

我的问题是——

当我们反序列化一个不可变对象(所有声明为最终的字段)时,相同的最终保证是否适用?

http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.3

(更新)

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6379948(反序列化错误)

当我们克隆一个不可变对象(所有声明为最终的字段)时,相同的最终保证是否适用?

4

2 回答 2

0

When deserializing an object, the only way you can get a reference to it is after deserialization has completed and it is returned. At that point, its fields have been assigned.

Generally, the only way to get a reference to an incompletely initialized object is if its superclass constructor passes a reference to this to another thread.

If the concern is that the values of mutable fields of the deserialized object not marked with volatile might be in the processor cache on one CPU and not flushed to main memory, I actually can't answer that with authority, but I would be very surprised if the guarantees were not the same as those of running a constructor.

于 2013-07-12T00:12:59.200 回答
0

If you pass an object to another thread using a thread safe collection or container, you will see the correct state for the class. This means the built in queues, synchronized collections, locked collections, atomic reference or volatile.

To even see such a problem you would have to be using an access which itself must not be thread safe as any write/read barrier you use, even indirectly, would ensure correct initialisation.

于 2013-07-06T22:19:33.280 回答