Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does garbage collection happen for a class with static data

I want to make some data easily available throughout my application. I have a few variables in a class with static data, which get written to and read from at several different points.

This worked fine for a while, but now at one point where I expect to be able to retrieve an ArrayList all I get is "null".

I am wondering if the static class has been sent to the "garbage collector". Not sure what's going on, if you can help that would be much appreciated.

like image 216
Ankur Avatar asked Jun 17 '09 06:06

Ankur


People also ask

Do static classes get garbage collected?

Since there's effectively always a "reference" to the static object, it will never get garbage collected.

Why static variables are not garbage collected?

Because static variables are referenced by the Class objects which are referenced by ClassLoaders. So, Static variables are only garbage collected when the class loader which has loaded the class in which static field is there is garbage collected in java.

What triggers garbage collection?

When a JVM runs out of space in the storage heap and is unable to allocate any more objects (an allocation failure), a garbage collection is triggered. The Garbage Collector cleans up objects in the storage heap that are no longer being referenced by applications and frees some of the space.

Where static variables stored in memory that area will be garbage collected?

Static variable are stored in PremGen space in memory, their values are stored in Heap.


2 Answers

you can try to make it final, and recompile the code in order to see if some other class CHANGES the reference to null:

public class Global {

    public final static List<String> data = new ArrayList<String>();

}

this allow to write:

Global.data.add("foo");

but not:

Global.data = null;
like image 142
dfa Avatar answered Oct 10 '22 04:10

dfa


I have a few variables in a static class, which get written to... at several different points.

As you are confessing yourself, so a null can be assigned to the variable at one or more of those different points. :)

like image 24
Adeel Ansari Avatar answered Oct 10 '22 04:10

Adeel Ansari