Search code examples
javagarbage-collectiongarbage

Can garbage collector run on Static class objects


I have to make class, who's object is never garbage collected . So If I give class as an static does it will avoid garbage collection on his objects,Or is ther any another way to do that ??


Solution

  • Short answer : No. Marking your class static may NOT save it from garbage collection

    Making a class static may avoid garbage collection for the particular class loader which was responsible for loading it. However, if this classloader gets opted for garbage collection, then all classes loaded via it ( static or non-static ) will also be garbage collected.

    Usually this is the case when you have multiple class loaders in your application.

    Other than that, an object ( any object ) is opted for garbage collection when it becomes unreachable

    From the JLS (source)

    A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector [...] Classes and interfaces loaded by the bootstrap loader may not be unloaded.