gpt4 book ai didi

java - 由于 Java/Android GC,是否有可能将整数重置为零?

转载 作者:行者123 更新时间:2023-11-29 06:42:11 25 4
gpt4 key购买 nike

我读过 blog post (对不起,它是用中文写的)作者说:

This is a web-related app, we declare some private variable, when user have done some operations, these variable will be set to some value for later use.

Normally the app is running well, but when we open some website with heavy JavaScript, our application starts to behave incorrectly and unexpected (without any Activity switching), we can not find why.

Finally, we found that this is caused by a integer variable has been set to zero. But we are very certain that our code won't reset it to zero, so there is only one possible conclusion: "In order to satisfy the resource required by WebView, Garbage Collector has collected our variable". So at last we set declare this variable as a static variable to avoid this problem.

坦率地说,这个“GC 将 int 设置为零”的论点与我的 Java 知识完全相反。

因为据我所知:

  1. Java GC的收集单元是object,原始类型int在Java中不是object。
  2. 实例变量的生命周期与所有者对象的生命周期相同,当该对象被 GC 回收时,该实例变量使用的内存将被释放。
  3. 即使该变量是 Integer 对象而不是原始 int 因此也可以被收集,只要存在对其的可访问引用,它就不会被收集。
  4. 即使我们使用 Wea​​kReference 来存储 Integer 引用以使 Integer 对象可回收,在 Integer 对象被回收之后,我们无论如何也无法访问该已释放对象的内存。

但我也担心是否有我没有考虑到的事情。

所以我对下面的问题很感兴趣:

  1. 是否存在因垃圾收集而可能将 int 或 Integer 对象重置为零的情况?
  2. 是否有可能 GC 只释放对象占用的部分内存空间(比如只释放一个实例变量),而不是释放整个对象?
  3. 是否可以引用已被垃圾收集的对象,如果我们取消引用它会发生什么?
  4. 假设变量被随机重置为零,并且不是由他们的代码引起的,这种情况最可能发生的情况是什么。虚拟机错误? GC错误? JIT 错误或其他任何问题?

最佳答案

I there any possible situation a int or Integer object could be reset to zero due to Garbage Collection?

如果持有 intInteger 的对象本身被垃圾收集并随后由应用程序代码重新创建,那么在外部看来 intInteger 已重置。

否则,没有。

Is it possible GC only freed partial space that an object takes, instead of full objects?

仅当您使用诸如 WeakReference 之类的东西作为与“部分空间”的连接时。

Is it possible to have a reference to a already garbage collected object

没有。如果你能到达它,它就不会被垃圾收集。

what will happen if we dereference it?

时空连续体将会破裂,终结我们所知的现实。

关于java - 由于 Java/Android GC,是否有可能将整数重置为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com