Java and memory allocation

Java Memory Management

This article will focus on Java memory management, how the heap works, reference types, garbage collection, and also related concepts.

Why Learn Java Memory Management?
We all know that Java itself manages the memory and needs no explicit intervention of the programmer. Garbage collector itself ensures that the unused space gets cleaned and memory can be freed when not needed. So what’s the role of programmer and why a programmer needs to learn about the Java Memory Management ? Being a programmer, you don’t need to bother with problems like destroying objects, all credits to the garbage collector. However the automatic garbage collection doesn’t guarantee everything. If we don’t know how the memory management works, often we will end up amidst things that are not managed by JVM (Java Virtual Machine). There are some objects that aren’t eligible for the automatic garbage collection.

Hence knowing the memory management is essential as it will benefit the programmer to write high performance based programs that will not crash, or if does so, the programmer will know how to debug or overcome the crashes.

Introduction:

In every programming language, the memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. However in Java, unlike other programming language, the JVM and to be specific Garbage Collector has the role of managing memory allocation so that the programmer needs not to. Whereas in other programming languages such as C the programmer has direct access to the memory who allocates memory in his code, thereby creating a lot of scope for leaks.

Читайте также:  Java log level finest

The major concepts in Java Memory Management :

Java Memory Structure:

JVM defines various run time data area which are used during execution of a program. Some of the areas are created by the JVM whereas some are created by the threads that are used in a program. However, the memory area created by JVM is destroyed only when the JVM exits. The data areas of thread are created during instantiation and destroyed when the thread exits.

JVM Memory area parts

Let’s study these parts of memory area in detail:

Heap :

  • It is a shared runtime data area and stores the actual object in a memory. It is instantiated during the virtual machine startup.
  • This memory is allocated for all class instances and array. Heap can be of fixed or dynamic size depending upon the system’s configuration.
  • JVM provides the user control to initialize or vary the size of heap as per the requirement. When a new keyword is used, object is assigned a space in heap, but the reference of the same exists onto the stack.
  • There exists one and only one heap for a running JVM process.

The above statement creates the object of Scanner class which gets allocated to heap whereas the reference ‘sc’ gets pushed to the stack.

Note: Garbage collection in heap area is mandatory.

Method Area:

  • It is a logical part of the heap area and is created on virtual machine startup.
  • This memory is allocated for class structures, method data and constructor field data, and also for interfaces or special method used in class. Heap can be of fixed or dynamic size depending upon the system’s configuration.
  • Can be of a fixed size or expanded as required by the computation. Needs not to be contiguous.

Note: Though method area is logically a part of heap, it may or may not be garbage collected even if garbage collection is compulsory in heap area.

JVM Stacks:

  • A stack is created at the same time when a thread is created and is used to store data and partial results which will be needed while returning value for method and performing dynamic linking.
  • Stacks can either be of fixed or dynamic size. The size of a stack can be chosen independently when it is created.
  • The memory for stack needs not to be contiguous.

Native method Stacks:

Also called as C stacks, native method stacks are not written in Java language. This memory is allocated for each thread when its created. And it can be of fixed or dynamic nature.

Program counter (PC) registers:

Each JVM thread which carries out the task of a specific method has a program counter register associated with it. The non native method has a PC which stores the address of the available JVM instruction whereas in a native method, the value of program counter is undefined. PC register is capable of storing the return address or a native pointer on some specific platform.

Working of a Garbage Collector:

  • JVM triggers this process and as per the JVM garbage collection process is done or else withheld. It reduces the burden of programmer by automatically performing the allocation or deallocation of memory.
  • Garbage collection process causes the rest of the processes or threads to be paused and thus is costly in nature. This problem is unacceptable for the client but can be eliminated by applying several garbage collector based algorithms. This process of applying algorithm is often termed as Garbage Collector tuning and is important for improving the performance of a program.
  • Another solution is the generational garbage collectors that adds an age field to the objects that are assigned a memory. As more and more objects are created, the list of garbage grows thereby increasing the garbage collection time. On the basis of how many clock cycles the objects have survived, objects are grouped and are allocated an ‘age’ accordingly. This way the garbage collection work gets distributed.
  • In the current scenario, all garbage collectors are generational, and hence, optimal.

Note: System.gc() and Runtime.gc() are the methods which requests for Garbage collection to JVM explicitly but it doesn’t ensures garbage collection as the final decision of garbage collection is of JVM only.

Knowing how the program and it’s data is stored or organized is essential as it helps when the programmer intends to write an optimized code in terms of resources and it’s consumption. Also it helps in finding the memory leaks or inconsistency, and helps in debugging memory related errors. However, the memory management concept is extremely vast and therefore one must put his best to study it as much as possible to improve the knowledge of the same.

Источник

Java Stack and Heap: Java Memory Allocation Tutorial

Stack in java is a section of memory which contains methods, local variables, and reference variables. Stack memory is always referenced in Last-In-First-Out order. Local variables are created in the stack.

What is Heap Memory?

Heap is a section of memory which contains Objects and may also contain reference variables. Instance variables are created in the heap

Memory Allocation in Java

Memory Allocation in Java is the process in which the virtual memory sections are set aside in a program for storing the variables and instances of structures and classes. However, the memory isn’t allocated to an object at declaration but only a reference is created. For the memory allocation of the object, new() method is used, so the object is always allocated memory on the heap.

The Java Memory Allocation is divided into following sections :

This division of memory is required for its effective management.

  • The code section contains your bytecode.
  • The Stack section of memory contains methods, local variables, and reference variables.
  • The Heap section contains Objects (may also contain reference variables).
  • The Static section contains Static data/methods.

Difference between Local and Instance Variable

Instance variable is declared inside a class but not inside a method

Local variable are declared inside a method including method arguments.

Difference between Stack and Heap

Click here if the video is not accessible

Let’s take an example to understand this better.

Consider that your main method calling method m1

In the stack java, a frame will be created from method m1.

Java Stack and Heap

The variable X in m1 will also be created in the frame for m1 in the stack. (See image below).

Java Stack and Heap

Method m1 is calling method m2. In the stack java, a new frame is created for m2 on top of the frame m1.

Java Stack and Heap

Java Stack and Heap

Variable b and c will also be created in a frame m2 in a stack.

Java Stack and Heap

Same method m2 is calling method m3. Again a frame m3 is created on the top of the stack (see image below).

Java Stack and Heap

Java Stack and Heap

Now let say our method m3 is creating an object for class “Account,” which has two instances variable int p and int q.

Here is the code for method m3

The statement new Account() will create an object of account in heap.

Java Stack and Heap

The reference variable “ref” will be created in a stack java.

Java Stack and Heap

The assignment “=” operator will make a reference variable to point to the object in the Heap.

Java Stack and Heap

Once the method has completed its execution. The flow of control will go back to the calling method. Which in this case is method m2.

Java Stack and Heap

The stack from method m3 will be flushed out.

Java Stack and Heap

Since the reference variable will no longer be pointing to the object in the heap, it would be eligible for garbage collection.

Java Stack and Heap

Once method m2 has completed its execution. It will be popped out of the stack, and all its variable will be flushed and no longer be available for use.

Eventually, the flow of control will return to the start point of the program. Which usually, is the “main” method.

What if Object has a reference as its instance variable?

public static void main(String args[]) < A parent = new A(); //more code >class A < B child = new B(); int e; //more code >class B < int c; int d; //more code >

In this case , the reference variable “child” will be created in heap ,which in turn will be pointing to its object, something like the diagram shown below.

Java Stack and Heap

  • When a method is called, a frame is created on the top of the stack.
  • Once a method has completed execution, the flow of control returns to the calling method and its corresponding stack frame is flushed.
  • Local variables are created in the stack
  • Instance variables are created in the heap & are part of the object they belong to.
  • Reference variables are created in the stack.

Источник

Оцените статью