Java / Garbage collection
The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application so that the resources be reclaimed and reused.
Garbage collection works by employing several GC algorithms, for example, Mark and Sweep.
Garbage Collector is the program running in the background that looks into all the objects in the memory and find out objects that are not referenced by any part of the program. All these unreferenced objects are deleted and space is reclaimed for allocation to other objects.
There are many kinds of garbage collector available in Java to collect different area of heap memory, some of them include serial, parallel and concurrent garbage collectors.
The basic way of garbage collection involves 3 steps:
- Marking is the first step where garbage collector identifies which objects are in use and which ones are not in use.
- Normal Deletion: Garbage Collector removes the unused objects and reclaim the free space to be allocated to other objects.
- Deletion with Compacting: After deleting unused objects, all the survived objects can be moved to be together. This will increase the performance of allocation of memory to newer objects.
Heap is divided into different generation, for example, new (young) generation, old generation and PermGen space.PermGen space is used to store class metadata and over filling of PermGen space can cause java.lang.OutOfMemoryError:PermGen space.
Young Generation : It is place where lived for short period and divided into 2 spaces:
- Eden Space : When object created using new keyword memory allocated on this space. Survivor Space : This is the pool which contains objects which have survived after java garbage collection from Eden space.
Old Generation : This pool is basically contain tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.
- Tenured Space: This memory pool contains objects which survived after multiple garbage collection means object which survived after garbage collection from Survivor space.
Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.
In Java8, PermGen is replaced with Metaspace which is very similar. Main difference is that Metaspace re-sizes dynamically.
Code Cache (Virtual or reserved) : HotSpot Java VM includes code cache area that has memory which will be used for compilation and storage of native code.
Yes, Java does automatic garbage collection, unlike other programming languages such as C where memory allocation and deallocation is a manual process.
An object becomes eligible for garbage collection when there is no reference for that object or it inaccessible by any live thread.
Cyclic reference where two objects are pointing to each other and there is no live reference for any of them, than both are eligible for GC.
Garbage collection thread is a daemon thread which will run by JVM based upon GC algorithm and when runs it collects all objects which are eligible for GC.
By enabling logging using -verbose:gc
or -XX:PrintGCDetails
it can be identified.
Minor collection prints GC if garbage collection logging is enabled, while Major collection prints Full GC.
There is no significant difference between System.gc() and Runtime.gc().
System.gc() internally calls Runtime.gc(). The only difference is System.gc() is a class method whereas Runtime.gc() is an instance method.
Runtime.gc() is a native method whereas System.gc() is non - native method which in turn calls the Runtime.gc().
Calling System.gc is more convenient than Runtime.gc as we call class method directly.
If garbage collection logging is enabled using -verbose:gc
, the word System will be printed when GC resulted by invoking System.gc method.
The java.lang.Object.finalize()
is called by the garbage collector on an object when garbage collection determines that there are no more references to that object. A subclass overrides the finalize method to dispose the system resources or to perform other cleanup actions.
protected void finalize()
Finalize method is also called as finalizer .
This method throws Throwable
exception. Exceptions occurred in finalize() method are not propagated and ignored by the garbage collector.
Just once.
By calling one of these methods, we can give a hint to the JVM, in order to start a garbage collection. However, it is up to the JVM to start the garbage collection immediately or later in time.
No, the object will be available for garbage collection only in the next cycle of the garbage collector.
The methods System.gc() and Runtime.gc() may be used to send request of Garbage collection to JVM but it is not guaranteed that garbage collection will happen.
We can call finalize method manually however that also does not guarantee object be garbage colllected.
No. It is developer responsibility to call finalize() method of the superclass, if not called explicitly, finalize of super class will never be called.
Call System.runFinalization() or
Runtime.getRuntime().runFinalization()
method.
Though not guaranteed, these methods increase possibility that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.
No.
If a Java class hold resource like input-output streams such as File, JDBC connection then you should override finalize and call its close() method from finalize. Though not guaranteed, finalize method acts as the last attempt to release the resources.
The overriden finalize method can be either protected or public.
Call superclass finalize method in the finally
block. This will guarantee that finalize of the parent class will be called in all condition except when JVM exits.
We may not, it is not a normal method and to be called only by JVM garbage collection thread.
Since finalize method execution is not guaranteed, use it only as the last attempt to resource not as first or only attempt.
- Local variable and input parameters of the currently executing methods.
- Active threads.
- Static field of the loaded classes.
- and JNI references.
Garbage collection can cause the JVM to pause all the application threads. Such pauses are called Stop-The-World (STW) pauses.
Ergonomics is the process by which the Java Virtual Machine (JVM) and garbage collection tuning, such as behavior-based tuning, improve application performance. The JVM provides platform-dependent default selections for the garbage collector, heap size, and runtime compiler. These selections match the needs of different types of applications while requiring less command-line tuning. In addition, behavior-based tuning dynamically tunes the sizes of the heap to meet a specified behavior of the application.
Throughput Garbage collector. Throughput GC is also known as parallel GC.
Maximum Pause Time Goal is the duration during which the garbage collector stops the application and recovers space that is no longer in use. The intent of the maximum pause time goal is to limit the longest of these pauses.
The maximum pause time goal is specified with the command-line option -XX:MaxGCPauseMillis=<nnn>
. This is interpreted as a hint to the garbage collector that pause times of nnn milliseconds or less are desired.
The throughput goal is measured in terms of the time spent collecting garbage and the time spent outside of garbage collection (referred to as application time). The goal is specified by the command-line option -XX:GCTimeRatio=<nnn>
.
In Java 7 and 8, it is parallel GC while from Java 9 onwards it is Garbage first (G1) GC.
The serial collector uses a single thread to perform all garbage collection work, which makes it relatively efficient because there is no communication overhead between threads. It is best-suited to single processor machines, also can be useful on multiprocessors for applications with small data sets (up to approximately 100 MB). The serial collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseSerialGC
.
Using the below JVM parameter will print the default ergonomic values.
java -XX: +PrintCommandLineFlags -version
Yes. GC handles circular reference.
Escape analysis is a technique by which the Java Hotspot Server Compiler can analyze the scope of a new object's uses and decide whether to allocate it on the Java heap.
Escape analysis determines the object's escape state which is one of the following.
GlobalEscape: An object escapes the method and thread. For example, an object stored in a static field, or, stored in a field of an escaped object, or, returned as the result of the current method.
ArgEscape: An object that is passed as an argument to a method but cannot otherwise be observed outside the method or by other threads.
NoEscape: An object that cannot escape the method or thread at all.