Java XMLDecode 和弱引用
我的问题是关于 Java 中弱引用的使用以及 XMLDecode 如何处理这个问题。假设我有两个对象,A 和 B。B 包含对 A 的弱引用。我使用 XMLEncode 将它们写入磁盘,稍后我使用 XMLDecode 将它们读回。
据我了解,没有设定的契约因为当垃圾收集器运行时,因此如果 XMLDecode 首先在 A 之前初始化 B,则在初始化 A 之前会出现一个短暂的窗口,此时弱引用可能会被无意破坏。这是正确的吗?
此外,如果 XMLDecode 碰巧在 B 中的弱引用中初始化 A,然后当我们尝试从 XMLDecode.readObject() 显式加载 A 时尝试使用 A 的此实例,那么如果垃圾收集器执行此操作,这肯定会导致空指针异常在初始化和赋值之间运行了吗?必须有一些东西可以避免这种情况,或者我对垃圾收集过程有误解。
My question is concerning the use of weak references in Java and how XMLDecode deals with this. Say I have two objects, A and B. B contains a weak reference to A. I use XMLEncode to write them to disk, and at a later date I use XMLDecode to read them back in.
As I understand it there is no set contract for when the garbage collector runs, so if XMLDecode begins by initializing B before A, there is a brief window before it initializes A when the weak reference can be broken unintentionally. Is this correct?
Furthermore, if XMLDecode happens to initialize A within the weak reference in B, and then attempts to use this instance of A when we attempt to load A explicitly from XMLDecode.readObject(), surely this could cause a null pointer exception if the garbage collector has run between the initialization and the assignment? There must be something in place to avoid this, or something I have misunderstood about the garbage collection process.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
A
是由B
实例内部存在的弱引用弱引用的对象,则当您序列化然后反序列化该结构时,初始化的顺序将是:B
的实例在
B
的实例内创建弱引用>
A
的对象在这些步骤中,GC 没有任何范围来收集 A 的实例
A
。If
A
is an object weakly referred to by a weak reference present inside an instance ofB
, when you serialize and then deserialize the structure , the sequence of initialization will be :Create instance of
B
Create the weak-ref inside instance of
B
A
No where in these steps is there any scope for GC to collect the instance of
A
.