Arpan Das
Arpan Das

Reputation: 1037

Is Method local variable will garbage collected if stored in static storage?

I am creating a client class, which will connect to different type of database. Following is the code snippet what I am trying to do.

public class Client{
    private static Map<ApplicationTypeEnum, Connection> connectionPool = new HashMap<>();

    public void init() throws Exception {

        try {
           Connection con1 = getConnection(someparams...);
           connectionPool.put("app-1",con1)
           Connection con2 = getConnection(someparams...);
           connectionPool.put("app-2",con2)
        } catch (Exception pe) {
            throw pe;
        }
    }
}

Now the Connection object are local to init, so is there any chance that the Connectionobjects will be garbage collected when control is out of init method.

Upvotes: 3

Views: 434

Answers (3)

davidxxx
davidxxx

Reputation: 131346

Is Method local variable will garbage collected if stored in static storage?

A variable is never garbage collected.
Only objects are garbage collected.
An object is illegible to be collected when it is not referenced by another other living object.
The object may be referenced by a static or an instance field. It doesn't matter for the GC.
But as a side note, static fields are not eligible to the GC.

In your actual code, the Connections you create in the init() method are referenced by the connectionPool static map.
So as the Connections are referenced by at least one living object, these are not eligible to be collected.

Upvotes: 2

Vasily Vlasov
Vasily Vlasov

Reputation: 3346

As long as any references exist pointing to these objects, they won't be garbage collected. In your case you have static variable connectionPool pointing to map, holding these objects. If you remove these objects from the above mentioned map or assign another map to connectionPool without these objects and will not have any other references to these objects, than yes, they will be collected.

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201447

No. Because you have stored the references in the static connectionPool they are still reachable, and are not eligible for garbage collection.

Upvotes: 1

Related Questions