简体   繁体   中英

Can String Literals become eligible for garbage collection. In this manner?

I have seen in a post https://stackoverflow.com/a/23934422/2194456

 class Test {
    String s = "1";
}
...
MyClassLoader cl = new MyClassLoader();
Object obj = cl.loadClass("Test").newInstance();
obj = null;
cl = null;
// now "1" is eligible for GC if no other class or object references it 

Does this really work ?

The only why for a string literal to be GCed would be if all classes referencing it were unloaded. And even then the particular garbage collector would have to be designed to delete interned strings, with not all are.

For a class to be unloaded it must be loaded with a user class loader and that loader and all objects and classes referencing the class must be freed/unloaded. This never happens by accident and is hard enough to get to happen on purpose.

(The above code attempts to do this, but, as I said, it's hard to do on purpose, so I can't say if it works or not.)

(And, as alluded to elsewhere, the ability to GC classes has been turned on and off several times in the history of the language and is very likely a startup option on some current JVMs.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM