Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is an instance variable of an object in Java stored on the stack or method area of the JVM?

Also, do we have different instance variable for multiple threads?

If it is stored in method area how is instance variable different from static variable storage?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

Stack and heap are the memories allocated by the OS to the JVM that runs in the system.Stack is a memory place where the methods and the local variables are stored. (variable references either primitive or object references are also stored in the stack). Heap is a memory place where the objects and its instance variable are stored.

So to sum it up:

  • Class objects, including method code and static fields: heap.
  • Objects, including instance fields: heap.
  • Local variables and calls to methods: stack

Also, do we have different instance variable for multiple threads?

Every thread will have a program counter (PC) and a java stack. PC will use the java stack to store the intermediate values, dynamic linking, return values for methods and dispatch exceptions. This is used in the place of registers.

Also for more about thread, you really should read this topic Where is Thread Object created? Stack or Heap?.

If it is stored in method area how is instance variable different from static variable storage?

As you can see above static fields are stored in heap. On the other hand, local variables are stored in stack.

//EDIT

According to the comments of Bruno Reis and Peter Lawrey, you should also read about Escape analysis

  1. Wikipedia
  2. Virtual Machine Performance Enhancements,Escape Analysis

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...