Showing posts with label JDK8Update. Show all posts
Showing posts with label JDK8Update. Show all posts

Friday, 3 July 2015

Memory types and Garbage Collector

➟ Purpose

      The main purpose of this article is to understand the structure of heap memory and how Garbage Collector works with it.

➟ Logical Structure of Memory (Image Source)



➟ Heap Memory

• The heap is the memory where all your objects will be stored. • The heap is created when the JVM starts up and may increase or decrease in size while the application runs.
• When the heap becomes full, garbage is collected. • We can define initial heap size using -Xms and maximum heap size using -Xmx.

➟ Areas (or Generations)

➤ New/Young/Nursery Generation(Space)

  • It's logical part of heap memory which is reserved for allocation of new objects.
  • When it becomes full, garbage is collected by running a special "young collection".
  • It can be define using -Xmn=512M

    ➤ Survivor1(From)

      • It's logical part of Young memory.
      • If object live after some fix amount of GC cycles, it will be move here from Eden space while performing Minor GC.

    ➤ Survivor2(From)

      • It's logical part of Young memory.
      • If object live after some fix amount of GC cycles, it will be move here from Survivor2 while performing Minor GC.

  • We can define the ratio between Eden space and survivor space using -XX:SurvivorRatio. For example if Young Generation size is 12m and VM switch is -XX:SurvivorRatio=2 then 6m will be reserved for Eden Space and 3m each for both the Survivor spaces. The default value is 8.

➤ Old/Tenured Generation(Space)

  • Object will be moved/promoted here when they are long live objects.
  • Object will be moved here while Major GC cycle.
  • The size of this space can be calculated as : Total Heap size - -Xmn (used for Old space).
  • We can also define ratio between old space and new space using -XX:NewRatio. for example, -XX:NewRatio=3 which is equivalent to Young:Tenured <=> 1:3 ratio.

➤ Perm Gen (The Permanent Generation) (before jdk 1.8)

  • It consists mostly of class declarations loaded and stored into it.
  • It stores Class and Methods' metadata like the name and fields of the class, methods with the method bytecode.
  • It stores Constant Pool information, object arrays and type arrays associated with a class and Just In Time compiler optimizations.
  • It stores String Pool information before jdk 7.
  • It can be specified using -XX:PermSize=256m (initial size) and -XX:MaxPermSize=356m

➟ Some Definitions/Terminologies

Major GC : Major GC is cleaning the Old/Tenured space.
Minor GC : Major GC is cleaning the Young(Eden and Survivor spaces) space.
Full GC : Full GC is cleaning the entire Heap – both Young and Old/Tenured spaces.
Application Pauses : While running GC, some application threads will pause, it's called Application Pauses.

➟ Java 8 Updates

➤ PermGen bybye..!, Welcome MetaSpace :)

  • The metadata has now moved to native memory to an area known as the “Metaspace”.
  • No longer have the PermGen, is not gone, so no more java.lang.OutOfMemoryError: PermGen space.
  • Similarly Metaspace introduced, so from now java.lang.OutOfMemoryError: Metaspace will be there, but it will be rare as Metaspace increase dynamically.
  • PermGen related JVM options will be just ignored
  • MetaSpace increases dynamically as needed, however MaxMetaspaceSize is available in case we want to limit it.
  • Slow compare to PermGen. (obviously, to get something, always need to pay something..!!)
  • More details : Reference

How String matters to Garbage Collection and Memory Leak in Java?

➟ What is Memory Leak?

      The application is unintentionally holding references to objects, and this prevents the objects from being garbage collected. This is the Java language equivalent of a memory leak.

➟ What is String Pool?

      String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

➤ Some Examples

• Both below are same. It will create new instance only if it is not available in pool, and then add in pool.
String s1 = "Vishal"; 
String s2 = new String("Vishal").intern();

• Below line will create new instance each time.
String s3 = new String("Vishal");

➟ String.substring Method

➤ Before JDK 7 update 6

• String was using counter, offset variable for managing the operations like Substring.
• String was sharing same char[] of original String while calling substring method, thus original String was not eligible for GC.
• Substring method was fast compare to new version.

➤ After JDK 7 update 6

• Counter and offset variables has been removed from String class.
• String is not sharing char[] of original String while calling substring method.
• Substring method is slow compare to old version, because it will create new char[] for each call of substring.

➟ Changes done for String.substring method update in JDK 7u6

➟ Memory Leak Bug Example in before JDK 7u6 (Source)

public class TestGC {
    private String largeString = new String(new byte[100000]);
    
    String getSmallString() {
// if caller stores this substring, this object will not be gc'ed
        return this.largeString.substring(0,2);
//      return new String(this.largeString.substring(0,2)); // no error here!
    }
    
    public static void main(String[] args) {
        java.util.ArrayList list = new java.util.ArrayList();
        for (int i = 0; i < 1000000; i++) {
            TestGC gc = new TestGC();
            list.add(gc.getSmallString());
        }
    }
}
➟ Java 8 Update

➤ String Deduplication :

• A new optimization has been made that enables the G1 collector to identify strings which are duplicated more than once across your heap.
• It will handle it by pointing into the same internal char[] array.
• It will avoid multiple copies of the same string from residing inefficiently within the heap.