Wednesday, 30 September 2015

Java Memory Management

Memory Management Part-II

Question : - What a Garbage Collector will do?

Answer:- Let's talk about Garbage Collector jobs
                Things to Consider
  • Stop the application events :- Garbage Collector pauses the entire application and at that            point it collects garbage.
  • Memory Fragmentation :- Memory fragmentation is when most of your memory is allocated in a large number of non-contiguous blocks and leaving a good percentage of our total memory unallocated, but that is unusable for most typical scenarios. This results in out of memory exceptions,When garbage collector runs does it defrag the memory fragment            to once or leave it to the latest state. 
  • ThroughPut :– how quickly can it run and how quickly can it collect?
  • Multi Core :- Now we have multiple processors or multiple threads Pauses are the times when an application appears unresponsive because garbage collection is occurring.
  • Promptness is the time between when an object becomes dead and memory becomes available, which is very important for distributed systems, including RMI.

 Question:- What is the way of Direct memory access in java?

Answer:- Java HotSpot VM contains a “backdoor” that provides a number of low-level operations to control threads and memory directly. This backdoor class sun.misc.Unsafe which is widely used by JDK itself in packages like java.nio or java.util.concurrent. This class provides an easy way to look into HotSpot JVM internals and this class can also be used for profiling and development tools.

Division of  java memory pool

The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. JVM Heap memory is physically divided into two parts –Young Generation and Old Generation.

  • Eden Space: The pool from which memory is initially allocated for most objects. Most initial objects allocated in Eden space.
  •  Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
  •  Tenured Generation: The pool containing objects that have existed for some time in the survivor space.
  •  Non-heap memory: Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size.
  •  Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
  • Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

For demonstartion how Garbage Collection works in Java

package com.gaurav.memorymanagement;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class GarbageCollectionExample {
private static Unsafe unsafe;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
unsafe = (Unsafe) field.get(null);
} catch (Exception e) {

public static long addressOf(Object o) throws Exception {
Object array[] = new Object[] { o };
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
int addressSize = unsafe.addressSize();
long objectAddress;
switch (addressSize) {
case 4:
objectAddress = unsafe.getInt(array, baseOffset);
case 8:
objectAddress = unsafe.getLong(array, baseOffset);
throw new Error("unsupported address size: " + addressSize);
return (objectAddress);

public static void main(String args[]){
for(int i=0; i< 40000; i++){
Object mine = new GCObjects();
long address = addressOf(mine);
}catch(Exception e){

class GCObjects {
long data;
long a;
long aa;
long aaa;
long aaaa;
long aaaaa;
long aaaaaa;
long aaaaaaa;
long aaaaaaaa;
long aaaaaaaaa;
long aaaaaaaaaa;
long aaaaaaaaaaa;
long aaaaaaaaaaaa;
long aaaaaaaaaaaaa;
long aaaaaaaaaaaaaa;
long aaaaaaaaaaaaaaa;
long aaaaaaaaaaaaaaaa;
long aaaaaaaaaaaaaaaaa;


Execution process - For demonstartion how Garbage Collection works in Java

            Java -cp . com.gaurav.memorymanagement.GarbageCollectionExample > GarbageCollectionExampleOutput.csv

This command will create a CSV file, which we can open with Microsoft Excel and represent those data using line chart. The representation will look like follows :

Thursday, 27 August 2015

Java Memory Management

Memory Management - PART - 1

Memory Management in java is responsibility of garbage collector. Garbage Collection is not the only form of Memory Management in Java. Real-time Specification for Java (RTSJ) is also being used for Memory Management. These efforts were mainly dedicated to real-time and embedded programming in Java for which GC was not suitable - due to performance overhead.

Understanding JVM Memory Model is very important if we want to know the working process of Java Garbage Collection.

Types of Garbage Collector : -

  • Do nothing : - It might just decide never to run and never to do anything, no memory gets free but it do stills gurantee to not collecting live objects.

  • Reference Counting garbage collector : - COM programming environment is the best example of Reference Counting Garbage collector. COM application may call 2 functions. First is Add Ref and second is Release. Add Ref increments the count of the object and Release decrease the count. When count goes to zero then ref is no longer been used or we can say that A reference count is maintained for each object on the heap. When an object is first created and a reference to it is assigned to a variable, the object's reference count is set to one. When any other variable is assigned a reference to that object, the object's count is incremented. When a reference to an object goes out of scope or is assigned a new value, the object's count is decremented. Any object with a reference count of zero can be garbage collected. When an object is garbage collected, any objects that it refers to have their reference counts decremented. In this way the garbage collection of one object may lead to the subsequent garbage collection of other objects.

  • Mark and Sweep : - To determine which objects are no longer in use, the JVM intermittently runs mark-and-sweep algorithm. Garbage collector runs in 2 phases, In mark phase it is marking that memory is still alive or this algorithm traverses all object references, starting with the GC roots, and marks every object found as alive and in sweep phase all of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.

  • Copying - Copying garbage collectors move all live objects to a new area and the old area is known to be all free space. This is not following any separate Mark and Sweep phases Objects are copied(these objects are discovered by the traversal from the root nodes) to the new area on the fly and forwarding ponters are left in their old locations and these pointers allows the garbage collector to detect references to objects that have already been moved. The garbage collector can then assign the value of the forwarding pointer to the references so they point to the object's new location.

  • Generational - Copying collectors spend much of their time for copying the same long-lived objects again and again. In order to address this inefficiency Generational collectors work with grouping objects by age and garbage collecting younger objects more often than older objects. This approach works by dividing the heap into two or more sub-heaps, each of which serves one "generation" of objects. The youngest generation is garbage collected most often. As most objects are short-lived, only a small percentage of young objects are likely to survive their first collection. Once an object has survived a few garbage collections as a member of the youngest generation, the object is promoted to the next generation: it is moved to another sub-heap.

  • Incremental - Rather than attempting to find and discard all unreachable objects at each invocation an incremental garbage collector just attempts to find and discard a portion of the unreachable objects. Because only a portion of the heap is garbage collected at each invocation, each invocation should in theory run in less time. A garbage collector that can perform incremental collections, each of which is guaranteed to require less than a certain maximum amount of time, can help make a Java virtual machine suitable for real-time environments.  

Reference taken from other sources