Methods in Java Classes: Memory

What happens in the areas of memory managed by Java when a method is invoked?

Overview

To understand what happens when a method is invoked, we must understand some basics of Java memory management. This understanding will not only help us visualize how control passes from one method to another, and the allocation of memory for primitives and object references in parameters, local variables, and return values in a method—but also help us when we tackle (eventually) more intimidating topics, such as recursion and concurrency.

Memory areas

There are 5 main areas of memory managed by the Java virtual machine; for now, we will focus on these 4:

  1. Class/method area

    When a class is loaded into memory, its static fields and the code of its methods (along with that of its constructors, static and non-static initializers, etc.) are loaded into this area of memory.

  2. Heap

    When an instance of any class (including any type of array) is created, the space for that instance’s state (data) is allocated in the heap as a contiguous block of memory. At certain moments (especially when a contigous block of heap memory is needed for an allocation, but no contiguous blocks of sufficient size are available), space that is no longer needed is reclaimed. This process of marking previously allocated memory as available for re-use, and moving objects around in the heap to create larger contiguous blocks of free memory for new object instances, is called garbage collection.

  3. Stack

    Each thread of executing code managed by the JVM has its own private stack, located in this area. Every method, while it is executing, has a stack frame—a block of memory on the stack, containing the parameters, local variables, and other working memory needed by the method. Each executing method has its own stack frame, which other methods can’t access in any way.

  4. Program counter (PC) registers

    The JVM maintains a program counter—a pointer to the current instruction in the code/method area—for each of the execution threads it manages. As Java bytecode instructions are executed, the associated PC register is updated.

Method invocation