1

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 ?

Community
  • 1
  • 1
LMK
  • 2,882
  • 5
  • 28
  • 52
  • 2
    No (only theoretically), neither `"1"` nor `"Test"`, as they - before java 8 - are stored in the permanent "generation" memory partition. (Oracle JVM) - Not important though. – Joop Eggen May 29 '14 at 14:42
  • On a tangent, setting `cl` and `obj` to `null` doesn't guarantee that `cl` is collectible. JVMs are allowed to skip unobserved assignments or reorder other operations before them. – Mike Samuel May 29 '14 at 14:51
  • take a look at my answer, it works, at least with my 1.7 HotSpot – Evgeniy Dorofeev May 29 '14 at 17:34
  • @JoopEggen -- Class unloading has been possible, off and on, since late Java 1 or early Java 2. – Hot Licks May 29 '14 at 17:42
  • @HotLicks class unloading yes, but string literals are kept separate in memory (`==`), shared among classes in the PermGen area, and hence are not garbage-collected.To my -not so deep - understanding. OF course technically GC could have been done. – Joop Eggen May 29 '14 at 18:51
  • @JoopEggen - String literals are not kept separate. Rather they are interned, but any string can be interned. As with class unloading, freeing interned strings has been possible off and on since fairly early. There are tradeoffs that must be made with other GC "knobs". – Hot Licks May 29 '14 at 18:55
  • @HotLicks the `String.intern()` mechanism I am aware of, The same string literals from two classes will yield one object. So, these literals can still be gc'ed (explicitly). Thanks, I will certainly in the near future look into that. – Joop Eggen May 29 '14 at 21:26

1 Answers1

1

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.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151