Reputation: 5460
Im currently undertaking a memory sweep of my application and i just have a quick question about what to do with public static
variables within a class when the class is no longer required. An example of this is network requests:
public class NetworkRequest {
public static String URL = "www.somestring.com/endpoint?withsomeparameters=true"
public void perform(){
// the rest of the request logic...
}
}
After i have initiated this class like so:
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.perform();
networkRequest = null;
Is my public static
field preventing this class from being correctly garbage collected?
Then the same question again for:
public static final
private static
private static final
. Thanks again for your help
Upvotes: 1
Views: 322
Reputation: 742
No, There is no problem with that static member. Garbage collector still can do its work for that object if there is no way to reach it.
All objects in Java exist either on the heap or on the stack. Objects are created on the heap with the new operator. A reference is then attached to them. If the reference becomes null or falls out of scope (e.g., end of block), the GC realizes that there is no way to reach that object ever again and reclaims it. If your reference is in a static variable, it never falls out of scope but you can still set it to null or to another object.
Static variables serve as "roots" to the GC. As a result, unless you explicitly set them to null, they will live as long as the program lives, and so is everything reachable from them.
Upvotes: 2
Reputation: 159086
No. Your class can be garbage collected when it is no longer used. That static field is the class using the String, not the String using your class.
Upvotes: 2