简体   繁体   中英

In Java, where is primitive static variables and static functions stored?

public Class A {
    public static String s = "s";
    public static int i = 0;
    public int j = 1;
    public static String getStaticString() {
        int k = 2;
        return s;
    }
    public String getString() {
        int l = 3;
        return "something";
    }
}

In Java , static variables are stored in Perm generation of Heap Segment , and primitive local variables are stored in Stack Segment . So where is i , j , k , l stored? Where is function getString() stored?

These are implementation details and we can't know for sure what each implementation does, without first reading and understanding its source code. As far as my knowledge and experience goes, the most reasonable things to assume (for a desktop JVM) are along these lines:

  • s and i are static variables. Static variables are probably allocated on the heap, in the permanent generation.
  • j is stored inside instances of class A . Class instances may live on the stack (if escape analysis for references can prove that the reference has automatic storage semantics - and they are small enough) or the heap (if escape analysis is not performed or is inconclusive or the instance is too large for the stack).
  • k is a local variable with automatic storage semantics, thus it should live on the stack. It's allocated when its containing method ( getStaticString ) is entered and it's deallocated when its containing method is exited.
  • l has the same semantics as k . The fact that its containing method ( getString ) isn't static, is irrelevant.
  • getString (and any other piece of user code, regardless of its linguistic attributes as static, non-static, etc) has two representations:
    • Its metadata and bytecode (AOT-compiled) are part of the class data of its containing class. Its lifetime in memory is likely to be linked with the loading/unloading of the class associated with this code, but not with any particular instance of that class. In other words, non-static methods aren't "created" every time you create an instance.
    • Its compiled code (JIT-compiled) should live permanently in a separate memory segment (a part of the JIT compiler's unmanaged heap, written to and then marked as executable), independent of the lifetime of the Java objects.

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