Showing posts with label Garbage Collection. Show all posts
Showing posts with label Garbage Collection. Show all posts

Wednesday, 12 July 2017

Java: What will happen when an infinite loop is called to create the objects in the same Reference?



package com.java.gc;
import java.util.List;
import java.util.ArrayList;

class Finalize extends Thread {
     int[] array;
     private int thread;
     public Finalize(int thread) {
           array = new int [1000000];
           this.thread = thread;
     }

     @Override
     public void run() {
           for (int i = 0; i < array.length; i++) {
                array[i] = i;
           }
     }
    
     @Override
     protected void finalize() throws Throwable {
           System.err.println("finalize " + thread);
     }
}

public class TestFinalize {
     public static void main(String[] args) {
           int counter = 0;
          
           List<Finalize> list = new ArrayList<Finalize>();
          
           while(true) {
                Finalize finalize = new Finalize(counter++);
               
                /** Uncomment the below line will lead to
                 * "java.lang.OutOfMemoryError: Java heap space"
                 *
                 *  However, when the line is commented then all
                 *  finalize object are eligible for garbage collection and finalize
                 *  method will be called for each object while garbage collection.
                 */
                //list.add(finalize);
                finalize.start();
           }
     }
}

Output:
When objects are eligible for garbage collection i.e when list.add(finalize) is commented.
finalize 0
finalize 19
finalize 20
finalize 21
finalize 14
finalize 15
finalize 16
finalize 17
finalize 18
finalize 9

Output:
When objects are eligible for garbage collection i.e when list.add(finalize) is uncommented.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     at com.java.gc.Finalize.<init>(TestFinalize.java:10)

     at com.java.gc.TestFinalize.main(TestFinalize.java:33)

Wednesday, 28 June 2017

Types of Java Garbage Collectors

In java, Garbage means unreferenced objects.

Garbage Collection is process of reclaiming the run-time unused memory automatically. In other words, it is a way to destroy the unused objects. Garbage collection is an automatic process in Java which relieves the programmer of object memory allocation and de-allocation chores.

Java has four types of garbage collectors:
1. Serial Garbage Collector
2. Parallel Garbage Collector
3. CMS Garbage Collector
4. G1 Garbage Collector.



Each of these four types has its own Pros and Cons. Most importantly, we can choose the type of garbage collector to be used by the JVM. This can be achieved by passing the choice as JVM argument. Each of these types differ largely and can provide completely different application performance therefore It is important to understand each of these types of garbage collectors and use it rightly based on the application.

1. Serial Garbage Collector
Serial garbage collector works by holding all the application threads. It is designed for the single-threaded environments. It uses just a single thread for garbage collection. This collector freezes all application threads whenever it’s working, which disqualifies it for all intents and purposes from being used in a server environment. It is best suited for simple command-line programs.

How to use it?
Turn on the -XX:+UseSerialGC JVM argument to use the serial garbage collector.

2. The Parallel / Throughput collector
Parallel garbage collector is also called as throughput collector. It is the default garbage collector of the JVM. Unlike serial garbage collector, its biggest advantage is that multiple threads scan to through and compact the heap. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection. The downside to the parallel collector is that it will stop application threads when performing either a minor or full GC collection. The parallel collector is best suited for apps that can tolerate application pauses and are trying to optimize for lower CPU overhead caused by the collector.

The parallel garbage collector uses multiple threads to perform the young genertion garbage collection.

By default on a host with N CPUs, the parallel garbage collector uses N garbage collector threads in the collection. The number of garbage collector threads can be controlled with command-line options:
-XX:ParallelGCThreads=<desired number>

On a host with a single CPU the default garbage collector is used even if the parallel garbage collector has been requested. On a host with two CPUs the parallel garbage collector generally performs as well as the default garbage collector and a reduction in the young generation garbage collector pause times can be expected on hosts with more than two CPUs. The Parallel GC comes in two flavours.

Usage Cases
The Parallel collector is also called a throughput collector. Since it can use multiple CPUs to speed up the application throughput. This collector should be used when a lot of work need to be done and long pauses is acceptable.
For example, batch processing like printing reports or bills or performing a large number of database queries.

How to use it?
Turn on the -XX:+UseParallelGC JVM argument to use the serial garbage collector.

With this command line option you get a multi-thread young generation collector with a single-threaded old generation collector. The option also does single-threaded compaction of old generation.

Command line to start the ParallelGCDemo:
java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseParallelGC -jar c:\javademos\demo\jfc\Java2D\ParallelGCDemo.jar

-XX:+UseParallelOldGC
With the -XX:+UseParallelOldGC option, the GC is both a multi threaded young generation collector and multithreaded old generation collector. It is also a multithreaded compacting collector. HotSpot does compaction only in the old generation. Young generation in HotSpot is considered a copy collector; therefore, there is no need for compaction.

Compacting describes the act of moving objects in a way that there are no holes between objects. After a garbage collection sweep, there may be holes left between live objects. Compacting moves objects so that there are no remaining holes. It is possible that a garbage collector be a non-compacting collector. Therefore, the difference between a parallel collector and a parallel compacting collector could be the latter compacts the space after a garbage collection sweep. The former would not.

Command line to start the ParallelOldGCDemo:
java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseParallelOldGC -jar c:\javademos\demo\jfc\Java2D\ParallelOldGCdemo.jar

The Concurrent Mark Sweep (CMS) Collector
CMS collector (also referred to as the concurrent low pause collector) collects the tenured generation. It attempts to minimize the pauses due to garbage collection by doing most of the garbage collection work concurrently with the application threads. Normally the concurrent low pause collector does not copy or compact the live objects. A garbage collection is done without moving the live objects. If fragmentation becomes a problem, allocate a larger heap.

Note: CMS collector on young generation uses the same algorithm as that of the parallel collector.

Usage Cases
The CMS collector should be used for applications that require low pause times and can share resources with the garbage collector.
Examples: Desktop UI application that respond to events, a web-server responding to a request or a database responding to queries.

Command Line Switches
To enable the CMS Collector use:
-XX:+UseConcMarkSweepGC

To set the number of threads use:
-XX:ParallelCMSThreads=<n>

Command line example to start the ConcMarkSweepDemo:
java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseConcMarkSweepGC -XX:ParallelCMSThreads=2 -jar c:\javademos\demo\jfc\Java2D\ConcMarkSweepdemo.jar

The G1 Garbage Collector
The Garbage First or G1 garbage collector is available in Java 7 and is designed to be the long term replacement for the CMS collector. The G1 collector is a parallel, concurrent, and incrementally compacting low-pause garbage collector that has quite a different layout from the other garbage collectors described previously.

Command Line Switches
To enable the G1 Collector use:
-XX:+UseG1GC

Command line example to start the G1GCDemo:
java -Xmx12m -Xms3m -XX:+UseG1GC -jar c:\javademos\demo\jfc\Java2D\ G1GCDemo.jar


Thursday, 25 May 2017

Can we execute the java program after calling System.exit(0)

Approach#1
Using ShutdownHook

class MyThread extends Thread { 
     public void run() { 
           System.out.println("After System exit call.");
     } 

public classTestSystemExit { 
     public static voidmain(String[] args)throws Exception { 

           Runtime runtime = Runtime.getRuntime(); 
          
           runtime.addShutdownHook(new MyThread()); 

           System.out.println("Before System exit call.");
           System.exit(0); 
          
     } 
}
Output:
Before System exit call.
After System exit call.

What is ShutDownHook?
Shutdown Hooks are a special construct that allow developers to plug in a piece of code to be executed when the JVM is shutting down.

Approach#2
We can achieve it by overriding the checkExit method of SecurityManager class.

importjava.security.Permission;

public classSystemExitBreaked {
     public static voidmain(String[] args) {
           System.setSecurityManager(new SecurityManager() {

                @Override
                public voidcheckPermission(Permission perm) {
                }

                @Override
                public void checkExit(int status) {
                     //throw new SecurityException(); // Line 10
                }

           });
           checkSystemExit();

     }

     public static voidcheckSystemExit() {

           System.out.println("Before System.exit(0)");
           try {
                System.exit(0);
           } catch(SecurityException se) {
                System.out.println("Inside the catch block !");
           }
           System.out.println("After System.exit(0)");

     }
}

Output: Before System.exit(0)

Now uncomment the line 10 i.e throw new SecurityException().

The new output will be:
Output:
Before System.exit(0)
Inside the catch block!
After System.exit(0)

Thursday, 18 May 2017

What is metaspace in Java?

Until Java 7, there was an area in JVM memory called PermGen, where JVM used to keep its classes. In Java 8, Permanent Generation (PermGen) space was completely removed and is replaced by a new space called Metaspace.

The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.

Metaspace by default auto increases its size (up to what the underlying OS provides), while PermGen always has a fixed maximum size. You can set a fixed maximum for Metaspace with JVM parameters, but you cannot make PermGen auto increase.




Object generations - Java heap terminology: young, old and permanent generations?

The heap is split into several different sections, called generations.

As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

1. Eden Space
2. Survivor Space
3. Tenured Generation
4. Permanent Generation, or PermGen.

When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.

There is also a fourth generation, called the Permanent Generationor PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool.

Note:
PermGen space is planned to be removed from Java 8 and will be replaced with a new space called Metaspace, which will be held in native memory.

Using the PermGen Space

For most applications, the PermGen area contains traditional class definitions, String constants, and not much else. Newer languages running on the JVM, such as Groovy, have the capability to create dynamic class definitions, and when used under load, this can fill up the PermGen space easily. You must be careful when creating many dynamic class definitions, and you may need to tweak the default memory allocation for PermGen space.
Related Posts Plugin for WordPress, Blogger...