0% found this document useful (0 votes)
2 views

Java-QA-GCMemory

The document discusses the necessity of Garbage Collection (GC) in Java, its drawbacks, and the structure of Java Heap. It explains various types of garbage collectors, memory management concepts, and how objects become eligible for GC. Additionally, it covers memory leaks, reference types, and the representation of strings in memory.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java-QA-GCMemory

The document discusses the necessity of Garbage Collection (GC) in Java, its drawbacks, and the structure of Java Heap. It explains various types of garbage collectors, memory management concepts, and how objects become eligible for GC. Additionally, it covers memory leaks, reference types, and the representation of strings in memory.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Java Q/A : Memory & GC

1) Why Garbage Collection is necessary in Java?

In programming languages such as C and C++, the developer


programmatically reclaims the space that is allocated to an object in the
memory. In Java programming, the user is not responsible for managing the
space memory used by the objects. In JVM, a garbage collection routine is
added as its part, which is responsible for identifying and deleting objects
that are no longer in use in memory.

2) What is the drawback to Garbage Collection?

The main drawback of Garbage Collection is that it freezes all those threads
which are currently active at the time of occurring memory recovery phase.
The garbage collection algorithms take time in seconds or minutes to run,
and due to this, garbage collection routines can't be scheduled.

3) Explain the structure of Java Heap.

A chunk of memory shared among all threads is referred to as Java Heap. In


Java, Heap is a combination of three generations such as new generation, old
generation and PermGen space.

4) Explain PermGen space in Java.

The internal representation of the Java classes held by JVM is included in the
PermGen space. PermGen space contains garbage data collected in the same
way as the heap's other parts (Young generation and Old generation)
collected.
5) Explain the difference between a minor, major and full garbage
collection.

There is no official documentation or specification which can define the


difference between major, minor and full garbage collection. We can define
each one of them in the following way:

1. Full garbage collection works on the tenured space.


2. Major garbage collection works on the survivor space.
3. Minor garbage collection works on the Eden space to perform a mark-
and-sweep routine.

6) Differentiate ParNew and DefNew Young Generation garbage


collectors.

ParNew and DefNew both are types of Young Generation garbage


collectors. A multi-threaded garbage collector that is used with the
concurrent Mark Sweep is referred to as a ParNew young generation
garbage collector, whereas a single-threaded garbage collector that is used
with the serial garbage collector is referred to as a DefNew young generation
garbage collector.

7) Explain the use of the Finalize() method of the garbage


collector.

The Finalize() method is called by the garbage collector before collecting any
object that is eligible for the garbage collector. The Finalize() method is used
to get the last chance to object to cleaning and free remaining resource.
8) Can we force the Garbage collector to run at any time?

No, we cannot force Garbage collection in Java. Although, we can request it


by calling system.gc() or its cousin Runtime.getRunitime().get(). It's not
guaranteed that GC will run immediately as a result of calling these methods.

9) Does Garbage collection occur in permanent generation space


in JVM?

Yes, Garbage collection can occur in PermGen space. If PermGen crosses a


threshold or it is full, it can trigger Full Garbage Collector.

10) What do you mean by mark-and-sweep?

Mark and Sweep are the two states of garbage collection. In the Mark stage,
JVM identifies whether an object is still needed or not. The object is marked
for garbage collection when the object is not needed.

In the Sweep stage, JVM performs memory reclamation and garbage


collection algorithms.

11) Explain the difference between Minor, Major, and Full


garbage collection.

There is no official documentation that can define the difference


between Minor, Major, and Full garbage collection. However, it is
commonly understood that:

1. The Mark and Sweep stages of garbage collection are performed on


the Eden space in Minor garbage collection.
2. The Major garbage collection works in the survivor space.
3. The Full garbage collection works on the tenured space.
12) What is a memory leak, and how does it affect garbage
collection?

A situation where a garbage collector fails to identify and remove an unused


object from memory is referred to as a memory leak.

The memory consumption is increased by the memory leak. After increasing


the memory consumption, JVM is forced to clear more space for new
objects. Mark and Sweep stages of garbage collection run more frequently. It
free up less memory each time these stages run until there is no heap space
left.

13) Can we trigger garbage collection from the code?

Yes, we can trigger the garbage collection by issuing a request to the JVM.
We use the System.gc() command for issuing the request. However, there is
no guarantee on when the JVM will respond to such a request.

14) Which part of the memory from Stack or Heap is involved in


GC?

A heap part of the memory is involved in GC.

15) Explain the responsibilities of GC.

The main responsibility of garbage collection is to free up unused memory.


GC ensures that the available memory will be used efficiently but does not
guarantee that there will be enough memory to run the program.
16) What is a daemon thread? Is GC a daemon thread?

A thread which runs behind the application for performing background


operations is referred to as a daemon thread.

Yes, GC is a daemon thread which starts by JVM.

17) Explain the ways for making an object eligible for GC when it
is no longer needed?

There are the following three ways to make an object eligible for GC:

By setting all available object references to null

When the purpose of creating an object is achieved, we can set the reference
of this object to null to make it available for GC.

1. public class GCExample1 {


2. // main() method start
3. public static void main (String [] args){
4. String strData = "Garbage Collector Example by javaTpoint.";
5. // strData is not eligible for garbage collector yet.
6. strData = null; // set reference of String object to null
7. // strData is now eligible for garbage collector
8. }
9. }

By making reference variable for referring to another object

Decouple the reference variable from the object and set it refer to another
object, so the object which it was referring to before reassigning is eligible
for Garbage Collection.

1. publc class GCExample2 {


2. // main() method start
3. public static void main(String [] args){
4. String strData1 = "Garbage Collector Example String1 by javaTpoint.";
5. String strData2 = "Garbage Collector Example String2 by javaTpoint.";
6. // print strData1
7. System.out.println(strData1);
8. //strData1 is not eligible for Garbage Collector yet
9. strData1 = strData2;
10. /* Now the strData1 variable that refers to the String object "Garbage Coll
ector Example2 String by javaTpoint." and the object "Garbage Collector Exam
ple String1 by javaTpoint." is not referred by any variable and hence is eligible
for Garbage Collector*/
11. }
12. }

By creating Islands of Isolation

When we have two instance variables referring to the instance of the same
class, and these two variables also refer to each other and the object referred
by these variables don't have any other valid reference, these two objects are
eligible for GC.

18) What is the advantage of the Garbage collection?

The main advantage of the automatic garbage collection in Java is that it


removes the burden of manual memory allocation and deallocation from us
so that we can focus on problem solving.

19) What is the purpose of overriding finalize() method?

The finalize() method in Java also called finalizer is a method defined in


java.lang.Object. It is called by Garbage collector just before collecting any
object which is eligible for GC. Thus finalize() method provides last chance to
object to do cleanup and free any remaining resource.
20) What is garbage collection time?

The more live objects are found, the longer the suspension, which has a direct
impact on response time and throughput. This fundamental tenet of garbage
collection and the resulting effect on application execution is called the
garbage-collection pause or GC pause time.

21) How Are Strings Represented in Memory?

A String instance in Java is an object with two fields: a char[] value field and
an int hash field. The value field is an array of chars representing the string
itself, and the hash field contains the hashCode of a string which is
initialized with zero, calculated during the first hashCode() call and cached
ever since. As a curious edge case, if a hashCode of a string has a zero value,
it has to be recalculated each time the hashCode() is called.
Important thing is that a String instance is immutable: you can’t get or
modify the underlying char[] array. Another feature of strings is that the
static constant strings are loaded and cached in a string pool. If you have
multiple identical String objects in your source code, they are all
represented by a single instance at runtime.

22) What Is a Stringbuilder and What Are Its Use Cases?

What Is the Difference Between Appending a String to a


Stringbuilder and Concatenating Two Strings with a +
Operator?

How Does Stringbuilder Differ from Stringbuffer?


StringBuilder allows manipulating character sequences by appending,
deleting and inserting characters and strings. This is a mutable data
structure, as opposed to the String class which is immutable.
When concatenating two String instances, a new object is created, and
strings are copied. This could bring a huge garbage collector overhead if we
need to create or modify a string in a loop. StringBuilder allows handling
string manipulations much more efficiently.
StringBuffer is different from StringBuilder in that it is thread-safe. If you
need to manipulate a string in a single thread, use StringBuilder instead.

23) What are the causes of java.lang.OutOfMemoryError


The error triggers when the application attempts to add more data into the heap space
area, but there is not enough space for it. JVM throws Java heap space error whenever
it reaches the heap size limit.

o Spike in data volumes: It is a situation when the application attempts to add


more data into the heap space, but there is not enough space for it.
o Memory Leaks: It is a programming error that leads your application to
consume more memory continuously. It can occur in many ways. It is a condition
when objects are no longer used by the application but garbage collector unable
to recognize it. You can use the memory management tool (like HP jmeter,
JProbe, and IBM Tivoli) which identifies useless objects and memory leaks.
Example

1. public class MemoryLeaksDemo


2. {
3. public static void main(String[] args)
4. {
5. int[] arr = new int[999999999]; //allocating memory to array
6. System.out.println("OutOfMemoryError");
7. }
8. }

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space


at MemoryLeaksDemo.main(MemoryLeaksDemo.java:5)

24) What Reference Types Java has ?


There are four types of references: Strong, Weak, Soft, and Phantom reference. The
difference among the types of references is that the objects on the heap they refer to
are eligible for garbage collecting under the different criteria.

Strong reference: It is very simple as we use it in our daily programming. Any object
which has Strong reference attached to it is not eligible for garbage collection. We can
create a strong reference by using the following statement:

1. StringBuilder sb= new StringBuilder();

Weak Reference: It does not survive after the next garbage collection process. If we
are not sure when the data will be requested again. In this condition, we can create a
weak reference to it. In case, if the garbage collector processes, it destroys the object.
When we again try to retrieve that object, we get a null value. It is defined
in java.lang.ref.WeakReference class. We can create a weak reference by using the
following statement:

1. WeakReference<StringBuilder> reference = new WeakReference<>(new Strin


gBuilder());

Soft Reference: It is collected when the application is running low on memory. The
garbage collector does not collect the softly reachable objects. All soft referenced
object s are collected before it throws an OutOfMemoryError. We can create a soft
reference by using the following statement:
1. SoftReference<StringBuilder> reference = new SoftReference<>(new StringB
uilder());

Phantom Reference: It is available in java.lang.ref package. It is defined


in java.lang.ref.PhantomReference class. The object which has only phantom
reference pointing them can be collected whenever garbage collector wants to collect.
We can create a phantom reference by using the following statement:

1. PhantomReference<StringBuilder> reference = new PhantomReference<>(ne


w StringBuilder());

Types of Garbage Collector


o Serial Garbage Collector
o Parallel Garbage Collector
o Concurrent Mark Sweep (CMS) Garbage Collector
o Garbage First (G1) Garbage Collector
o Z Garbage Collector

The performance and working of each garbage collector are completely


different. It has its own pros and cons. Java allows us to choose any one
garbage collector that is to be used by the JVM. For the selection of GC, we
need to pass JVM arguments. It is difficult to select the right garbage collector
for the application. Let's discuss each garbage collector one by one.

Serial Garbage Collector


Serial Garbage collector is well-matched for single-threaded environments. It uses
the only thread for garbage collection. It works by holding all the threads of an
application. It means that threads of the application freeze by the serial garbage
collector during the garbage collection process and the process is known as stop the
world event. Avoid the use of serial GC in the server environment. We can use it for
simple programs. If you want to use the serial garbage collector, execute the -
XX:+UseSerialGC JVM argument to activate it.

Parallel Garbage Collector


Parallel Garbage Collector is the default GC used by the JVM. The working of the
parallel garbage collector is the same as the serial garbage collector. The only
difference between serial and parallel garbage collector is that serial garbage collector
uses a single thread for garbage collection process while the parallel garbage collector
uses multiple threads for the garbage collection. Parallel GC can use multiple CPUs to
speed up the application throughput. So, it is also known as throughput collector. It
is used if we want to execute a long process (like batch processing) and where long
pauses are acceptable. If you want to use the parallel garbage collector, execute the -
XX:+UseParallelGC JVM argument to activate it.
We can also use the following JVM arguments in parallel GC:

JVM Argument Description

-XX:ParallelGCThreads=<n> It controls the number of GC threads (n)

-XX:MaxGCPauseMillis=<t> It specifies the maximum pause time*.

-XX:GCTimeRatio=<n> It specifies the maximum throughput tar

*Pause Time: The gap between two GC.

**Throughput Target: The time spent during the garbage collection versus the time
spent outside of garbage collection is called throughput target.

Concurrent Mark and Sweep (CMS) Garbage Collector


CMS uses multiple threads that scan the heap and during the scanning, it marks the
instances for eviction, after scanning, it sweeps the marked instances. It does not freeze
the application's threads during the garbage collection. GC threads concurrently
execute with the application's threads. For this reason, it uses more CPU in comparison
to other GC. It is also known as the concurrent low pause collector. It also freezes all
the threads of the application only if it satisfies the following two scenarios:

o while marking the referenced objects in the tenured generation region.


o if any change is made to the heap memory in parallel during the garbage
collection process.

AD

We can use multiple CPUs for better application throughput. We should use a CMS
garbage collector if we have more CPUs for use. Hence, it has an advantage over the
parallel garbage collector. If you want to use a CMS garbage collector, execute the -
XX:+USeParNewGC JVM argument to activate it. We can also set the number of GC
threads by using the -XX:ParallelCMSThreads=<n> JVM argument.

Note: The JVM argument -XX:+UseConcMarkSweepGC has been deprecated because a


warning message is issued when it is requested on the command line.

Garbage First (G1) Garbage Collector


The G1 garbage collector is used if we have a large (more than 4GB) memory (heap
space). It divides the heap into equal-sized (usually 1MB to 32MB) chunks, prioritizes
them, and then performs the parallel garbage collection on that chunks based on the
priority.

The Eden, survivors, and old areas use this equal-sized region for the memory
allocation of the objects. Apart from these memory regions, there are two more types
of regions presented in the G1 GC:

o Humongous: It is used if the object sized is large.


o Available: It represents the unoccupied space.

G1 GC shows a concurrent global marking phase to determine the live and dead objects
throughout the heap. After the completion of the mark phase, G1 collects the
information of regions that contains the most garbage objects. After that these regions
are swept first. If you want to use the G1 garbage collector, execute the -
XX:+UseG1GC JVM argument to activate it.

Stop the World Event


It is a situation when the garbage collector performs the garbage collection (GC) and
stops all the application's threads until the GC process is not completed. The process
is known as Stop the World (STW) events.

Z Garbage Collector
ZGC is a scalable low-latency garbage collector that debuted in Java 11 as
an experimental option for Linux. JDK 14 introduced ZGC under the
Windows and macOS operating systems. ZGC has obtained the production
status from Java 15 onwards.
ZGC performs all expensive work concurrently, without stopping the
execution of application threads for more than 10 ms, which makes it
suitable for applications that require low latency. It uses load barriers with
colored pointers to perform concurrent operations when the threads are
running, and they’re used to keep track of heap usage.
Reference coloring (colored pointers) is the core concept of ZGC. It means
that ZGC uses some bits (metadata bits) of reference to mark the state of
the object. It also handles heaps ranging from 8MB to 16TB in size.
Furthermore, pause times don’t increase with the heap, live-set, or root-set
size.
Similar to G1, Z Garbage Collector partitions the heap, except that heap
regions can have different sizes.
To enable the Z Garbage Collector, we can use the following argument
in JDK versions lower than 15:
java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC Application.javaCopy
From version 15 on, we don’t need experimental mode on:
java -XX:+UseZGC Application.javaCopy
We should note that ZGC isn’t the default Garbage Collector.

JIT in Java
When we write a program in any programming language it requires converting that
code in the machine-understandable form because the machine only understands the
binary language. According to the programming languages, compiler differs. The
compiler is a program that converts the high-level language to machine level code.
The Java programming language uses the compiler named javac. It converts the high-
level language code into machine code (bytecode). JIT is a part of the JVM that
optimizes the performance of the application. JIT stands for Java-In-Time Compiler.
The JIT compilation is also known as dynamic compilation. In this section, we will
learn what is JIT in Java, its working, and the phases of the JIT compiler.

What is JIT in Java?


JIT in Java is an integral part of the JVM. It accelerates execution performance many
times over the previous level. In other words, it is a long-running, computer-intensive
program that provides the best performance environment. It optimizes the
performance of the Java application at compile or run time.

The JIT compilation includes two approaches AOT (Ahead-of-Time compilation)


and interpretation to translate code into machine code. AOT compiler compiles the
code into a native machine language (the same as the normal compiler). It transforms
the bytecode of a VM into the machine code. The following optimizations are done by
the JIT compilers:

o Method In-lining
o Local Optimizations
o Control Flow Optimizations
o Constant Folding
o Dead Code Elimination
o Global Optimizations
o Heuristics for optimizing call sites

Advantages of JIT Compiler

o It requires less memory usages.


o The code optimization is done at run time.
o It uses different levels of optimization.
o It reduces the page faults.

AD

Disadvantages of JIT Compiler

o It increases the complexity of the program.


o The program with less line of code does not take the benefit of the JIT compilation.
o It uses lots of cache memory.

Working of JIT Compiler


If the JIT compiler environment variable is properly set, the JVM reads the .class file
(bytecode) for interpretation after that it passes to the JIT compiler for further process.
After getting the bytecode, the JIT compiler transforms it into the native code
(machine-readable code).

o Java Development Kit (JDK) provides the Java compiler (javac) to compile the Java
source code into the bytecode (.class file). After that, JVM loads the .class file at runtime
and transform the bytecode into the binary code (machine code). Further, the machine
code is used by the interpreter.
o We know that the interpretation of Java bytecode reduces the performance of the
native application. It is the reason to implement the JIT compiler. The JIT compiler
accelerates the performance of the application by compiling the bytecode into native
machine code.
o It is enabled by default when a method is invoked. The JVM directly invokes the
compiled code of the method without interpreting it. It does not require much memory
usage.

Therefore, the JIT compiler boosts the performance of the native application. We can
understand the working of the JIT compiler with the help of the following flow chart.
The following figure shows the functional relationship of the JIT compiler
with JRE and JVM.
Optimization Levels
It is also known as the optimization level. Each level provides a certain level of
performance. JIT compiler provides the following level of optimization:

o Cold: It used during the startup of the large Java application. The goal is to achieve the
best-compiled code speed.
o Warm: After the starting of the Java application, most of the methods compiled when
they reach the invocation threshold.
o Hot: The methods that consume more than 1% are scheduled for hot compilation.
o Very Hot: The method scheduled for a very hot if they are not scorching but hot.
o Scorching: The methods that consume more than 5% are scheduled for scorching
compilation.

The default and initial optimization levels are warm. We get better performance if the
optimization level is hotter but it increases the cost in terms of memory and CPU.

At the higher optimization level, the virtual machine uses a thread called sampling. It
identifies the methods that take a long time to execute. The higher optimization level
includes the following techniques:

o Escape Analysis
o Partial Redundancy Elimination

The above techniques use more memory and CPU to improve the performance of the
Java application. It increases the cost of compilation but compensates for performance.

You might also like