WeakReference string didn't garbage collected? How?

感情迁移 提交于 2019-11-29 08:06:05

It is NOT because of string pooling per se.

The real reason is that the ReferenceTest class has an implicit hard reference to the String object that represents the "I'm here"literal. That hard reference means that the weak reference in sr won't be broken by the garbage collection1.

In fact:

  • The implicit reference would be necessary, even if String objects corresponding to literals weren't pooled. (They are pooled ... the JLS effectively requires this ... but I'm saying the references would required even if they weren't. The alternative would be for Java to mint a fresh String object each time a string literal expression was evaluated. That would be horribly inefficient!!)

  • The string pool internally uses a form of weak reference ... so that unreferenced interned strings can be garbage collected. If that weren't the case, then every new interned string would be a memory leak.

Anyway ... if you carefully construct a string without using a string literal and intern it, like this:

    char[] chars = {'a', 'b', 'c'};
    WeakReference r = new WeakReference(new String(chars).intern());

... you should find that the weak reference is (eventually) broken. (It might take a couple of GC cycles though.)


1 - In theory, causing the class to be unloaded and garbage collected could get rid of the last reachable hard reference to that String literal. However, if that happened in this case, you'd be past the point at which you'd be able to observe the state of the WeakReference object. At least, in with your example code. Besides, unless you boot your JVM with a custom class loader, I don't think it would be possible to cause the unloading of the entrypoint class. It's not the kind of thing that is easy, or useful to do.

It is becuase of string pooling.When you create string with new operator, it will get created in pool and available for normal garbage collection.But when you define string as literal, it will get created in string pool, and it wont get garbage collected with normal gc operation

Static variables are Garbage Collected only when the class is unloaded. Therefore you can see that the value of the static variable is still printed even after you manually triggered garbage collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!