Vaibhav Raj
Vaibhav Raj

Reputation: 2232

Static variables in POJO and garbage collection of objects and classes

I have written a base class for making request to repositories. It has a static field which is being used for some purpose in the application.

public abstract class RepositoryRequest {
    private static String version;

    {
        version = 2.0; //Actual read is happening from some configuration file.
    }

    protected String getVersion() {
        return version;
    }
}

We have multiple request POJOs which extend this abstract class

public class ARepositoryRequest extends RepositoryRequest {
    //Some properties here
    @Override
    public String toString() {
        return "Some string generated by some logic" + getVersion();
    }
}

Similarly other classes are also extending and overriding toString() method.

I have some doubts over garbage collection for these POJO objects:

1. Would this kind of usage of static variable will not let the POJO objects garbage collected?
2. Is there any issue with Objects/Classes in their garbage collection?

Upvotes: 2

Views: 2060

Answers (2)

DNA
DNA

Reputation: 42607

No, the static field will not prevent garbage collection of your subclasses (if it did, this would be a major problem, making static fields almost unusable in a garbage-collected language!)

You can test this by adding a finalizer to your classes, then create a bunch of them in a loop, calling System.gc() to provoke garbage collection. If your finalize() method prints out a message, you can see that GC is occurring.

protected void finalize() throws Throwable {
    System.out.println("Finalize!");
}

The reason is that the static field belongs to the class object (RepositoryRequest). This class can't be garbage collected while any of its instances exist, and typically classes aren't unloaded anyway, unless their ClassLoader is garbage collected, which is unusual.

However, all of the memory allocated to each of the instances can be safely reclaimed without having any effect on the class object.

There are situations where static members can prevent GC of other data; for example, if you cache all of the instances of a class in an ordinary Collection as a static field, then they can't be GCd (because there are still 'live' references to them).

Upvotes: 1

sam
sam

Reputation: 4397

Question already answered here: Are static fields open for garbage collection?

Copying answer: "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. "

Upvotes: 1

Related Questions