Java XMLDecode 和弱引用

发布于 2024-12-09 19:19:17 字数 390 浏览 3 评论 0原文

我的问题是关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-12-16 19:19:17

如果 A 是由 B 实例内部存在的弱引用弱引用的对象,则当您序列化然后反序列化该结构时,初始化的顺序将是:

  1. < p>创建 B 的实例

  2. B 的实例内创建弱引用

    >

  3. 创建 A 的对象
  4. 将第 2 步中的弱引用设置为第 3 步中初始化的对象。

在这些步骤中,GC 没有任何范围来收集 A 的实例A

If A is an object weakly referred to by a weak reference present inside an instance of B , when you serialize and then deserialize the structure , the sequence of initialization will be :

  1. Create instance of B

  2. Create the weak-ref inside instance of B

  3. Create the Object of A
  4. Set the weak ref in step 2 to object initialized in step 3.

No where in these steps is there any scope for GC to collect the instance of A.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文