Nov 5, 2017

Understanding JVM: Memory Areas in JVM - Part 2

Stack memory

  • It is maintained per thread, i.e., for every thread in Java, JVM will create a separate stack at the time of thread creation.
  • Each and every method call performed by the thread will be stored in stack including local variable also.
  • After completing a method, the corresponding entry from the stack will also be removed. Thus, once all method calls are completed, stack memory will become empty.
  • This empty stack will be destroyed by JVM before terminating the thread.
  • Data stored inside stack is private to corresponding thread only and hence thread-safe.
  • Each entry inside stack is called stack frame/activation record.

Stack Frame structure

Each Stack Frame has 3 parts:
  1. Local Variable Array,
  2. Operand Stack, and
  3. Frame Data
    Local Variable Array
    • It contains all parameters and local variables of the memory.
    • Each slot in the array is of 4 bytes.
    • Type
      • int, float, object -> 1 slot (4 bytes)
      • double, long -> 2 slots (8 bytes)
      • byte, short, char -> converted to int before storing -> 1 slot (4 bytes)
      • boolean -> JVM dependent -> generally 1 slot
    Operand Stack
    • It stores intermediate values.
    • JVM uses operand stack as workspace.
    • Some instructions can push values to operand stack, some instructions can pop values, and some can performance required operations.
    Lets take an example to understand the process. Suppose a program adds 2 values, say 40 and 60.
    JVM instructions will look something like:
    iload - 0 // loads 40
    iload - 1 // loads 60
    iadd // adds 40 and 60
    istore -2 // store the result

    Following is the state if Local Variable Array after first 2 load instructions.
    Local Variable Array

    Values are also loaded in Operand Stack for addition. 
    Operand Stack


    Finally, sum is  pop out from the operand stack and put into local variable array.
    Local Variable Array

    Finally the third component in the frame is Frame Data.

    Frame Data

    • It contains all symbolic references related to the method.
    • Contains references to exception table and will provide corresponding catch block information in case of exception.
    This is all about Stack Memory. Hopefully, it helps.
    Next section will cover the other 2 memory areas, PC registers and native method stack.

    If you like reading our articles, do follow at +Java Territory / Java Territory.

    0 comments:

    Post a Comment