为什么Java的基于价值的类不能被序列化? [英] Why should Java's value-based classes not be serialized?
问题描述
由于Version 8 Java具有 的概念基于价值的类。这是为了准备未来的版本,很可能会定义值类型。两个定义/描述都提到序列化(我添加的粗体):
Since Version 8 Java has the concept of value-based classes. This is in preparation of a future version which will most likely allow the definition of value types. Both definitions/descriptions mention serialization (bold face added by me):
关于现有的基于价值的类:
About the existing value-based classes:
如果程序试图将两个引用区分为基于值的类的相等值,无论是直接通过引用相等还是间接通过引发同步,身份哈希,序列化,或任何其他身份敏感机制。
A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization, or any other identity-sensitive mechanism.
关于未来的价值类型:
通过System.identityHashCode提供的对象的默认基于身份的哈希代码也不适用于值类型。像序列化这样的基于身份的区别对象的内部操作要么不适用于值(因为它们不适用于基元),要么它们会使用值类型的hashCode提供的基于值的区别方法。
The default identity-based hash code for object, available via System.identityHashCode, also does not apply to value types. Internal operations like serialization which make identity-based distinctions of objects would either not apply to values (as they do not apply to primitives) or else they would use the value-based distinction supplied by the value type’s hashCode method.
因为未来的JVM实现可能不会使用基于值的类的对象头和引用指针,所以一些限制很明显。 (例如,没有锁定JVM必须不支持的标识。锁定的引用可以被删除并在以后被另一个替换,这使得释放锁定毫无意义并将导致死锁)。
Because future JVM implementations might not use object headers and reference pointers for value-based classes, some of the limitations are clear. (E.g. not locking on an identity which the JVM must not uphold. A reference on which is locked could be removed and replaced by another later, which makes releasing the lock pointless and will cause deadlocks).
但我不知道序列化如何发挥作用。为什么它被认为是身份敏感机制?为什么基于身份的对象区分?
But I don't get how serialization plays into this. Why is it considered an "identity-sensitive mechanism"? Why does it "make identity-based distinctions of objects"?
推荐答案
序列化使用 System.identityHashCode
(通过 IdentityHashMap
)确保反序列化产生的对象图的拓扑在拓扑上等同于输入的拓扑图形。
Serialization uses System.identityHashCode
(via IdentityHashMap
) to ensure that the topology of the object graph resulting from deserialization is topologically equivalent to that of the input graph.
这篇关于为什么Java的基于价值的类不能被序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!