Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static fields open for garbage collection?

Given an hypothetical utility class that is used only in program setup:

class MyUtils {    private static MyObject myObject = new MyObject();    /*package*/static boolean doStuff(Params... params) {        // do stuff with myObject and params...    } } 

will myObject be garbage collected when it is no longer being used, or will it stick around for the life of the program?

like image 385
Michael Deardeuff Avatar asked Jan 17 '09 09:01

Michael Deardeuff


People also ask

When should you not use garbage collection?

Show activity on this post. The obvious cases for not using garbage collection are hard realtime, severely limited memory, and wanting to do bit twiddling with pointers.

Which method is used for garbage collection?

gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.

How does garbage collection work when it will be triggered?

At a certain point in time, an event happens that triggers garbage collection. To clear the memory, application threads have to be stopped. This is where the work of your application stops and the next steps start. The garbage collector marks objects that are no longer used and reclaims the memory.


1 Answers

Static variables cannot be elected for garbage collection while the class is loaded. They can be collected when the respective class loader (that was responsible for loading this class) is itself collected for garbage.

Check out the JLS Section 12.7 Unloading of Classes and Interfaces

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.

like image 142
bruno conde Avatar answered Oct 21 '22 07:10

bruno conde