Does the garbage collector contain static variables or methods in java?

I am creating a demo program for an example to understand how I can free a reference to static variables, methods in java using the garbage collector?

I use Weak Reference to prevent garbage collection.

Sample Class

 public class Sample { private static String userName; private static String password; static { userName = "GAURAV"; password = "password"; } public static String getUserName(){ return userName; } public static String getPassword(){ return password; } } 

User class

 import java.lang.ref.WeakReference; public class User { public static void main(String[] args) { /** * Created one object of Sample class */ Sample obj1 = new Sample(); /** * I can also access the value of userName through it class name */ System.out.println(obj1.getUserName()); //GAURAV WeakReference<Sample> wr = new WeakReference<Sample>(obj1); System.out.println(wr.get()); // com.test.ws.Sample@f62373 obj1 = null; System.gc(); System.out.println(wr.get()); // null /** * I have deallocate the Sample object . No more object referencing the Sample oblect class but I am getting the value of static variable. */ System.out.println(Sample.getUserName()); // GAURAV } } 
+7
source share
4 answers

static fields are associated with a class, not a single instance.

static fields are cleared when the ClassLoader that holds the class is not loaded. In many simple programs, this will never be.

If you want the fields to be associated with the instances and to be cleared, the instance is cleared, create the instance fields, not static ones.

+16
source

System.gc () does not force the garbage collector to start. This is just a JVM suggestion, which is probably the best time to start a garbage collector. See This Question - When System.gc () Does Something

+4
source

Except for a program to answer your question

  • Not. Methods are not garbage collection because they do not exist on the heap in the first place.

  • Static variables refer to an instance of the class and will not be loaded with garbage after loading (for most common class loaders)

+4
source

You must understand that System.gc(); does not call the garbage collector. He just politely asks GC to remove the garbage. GC decides what to do and when to start. Therefore, do not expect that you will immediately see the effect when you call System.gc(); by assigning null variable, etc.

GC deletes all objects that cannot be accessed. Therefore, if the code exits the block where the variable was defined, the object can be deleted. Applying a null value removes the link. A weak link does not prevent the GC from deleting the object.

I hope this explanation helps.

+3
source

All Articles