简体   繁体   中英

Memory Scope of Static Members in JAVA

This question is regarding memory management & GC in java.

Since java does not have true static classes like C#, what is the scope of static members in a class such as below:

public class Test {
public static String myVariable;
}

Lets say Test.myVariable is set / called in another class Foo.

Is Test.myVariable kept alive for as long as Foo is alive?

OR

Will Test.myVariable be kept alive for as long as the application domain is ?

When would myVariable go out of scope ?

I guess you mean when it will be available for the garbage collection.static members are candidate for garbage collection when the class loader which was responsible for loading the class is itself a candidate for garbage collection. For example suppose class Test was loaded by a class loader object say loader1.So when loader1 is eligible for GC then class Test and its static variable ,in this case myVariable are also eligible for GC Check out here

public access means it is available for all. There is no distinction of public between static and instance variables.

When would myVariable go out of scope ?

Not sure what you mean by variable going out of scope. Scope is public so it will be available everywhere. JVM lifetime in terms of garbage collection, depends on the reference to the class.

your class is public. your static member is public. It will not go out of scope.

I understand your concern is to when it is garbage collected. Before proceeding ahead you need to understand memory management

Note that only the variables and their technical values (primitives or references) are stored in PermGen space.

If your static variable is a reference to an object that object itself is stored in the normal sections of the heap (young/old generation or survivor space). Those objects (unless they are interal objects like classes etc.) are not stored in PermGen space.

Example:

static int i = 1; //the value 1 is stored in the permgen section 
static Object o = new SomeObject(); //the reference(pointer/memory address) is stored in the permgen section, the object itself is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM