Memory Leaks in Java
What is a memory leak?
A memory leak is repetitive allocation of memory without consequential release of it when no longer used, leading to increase in consumption of memory. This may not be a common scenario in most Java standalone applications because Java has inbuilt Garbage Collection.
Garbage Collection in Java
Objects in Java are stored in Heap space , while static members are stored in memory area of the Java memory space. In java automatic Garbage collection is done using the Garbage Collection daemon thread.Whenever the object is not referenced by the code it becomes a candidate for garbage collection. Before removing an object from Garbage Collection thread invokes finalize() method of that object so that it can perform any sort of cleanup.
As a programmer you cannot invoke Garbage collection thread it will get invoked only if the JVM thinks that it needs Garbage Collection based on the Java Memory Space. You can invoke System.gc() or Runtime.gc() to send request to Garbage Collection but it is not guaranteed that Garbage Collection thread will be invoked.
Types of Garbage Collection in Java
Serial GC -
- With the serial GC it uses internal logic for Garbage collection but in addition , it uses a compaction logic where it collects all the objects to the upper part of the heap, so that the new objects are allocated in continuous locations.
Concurrent Low Pause Collector-
- This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.