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

GarbageCollectionExample.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");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}

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);
break;
case 8:
objectAddress = unsafe.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}
return (objectAddress);
}

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

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 :