Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Garbage Collection in Java (1)

Garbage collection in Java is an automatic memory management process that identifies and removes unused objects from the heap to free up memory, unlike manual memory management in C/C++. It operates through minor and major garbage collection activities, with the garbage collector running as a background daemon thread. The process enhances memory efficiency, prevents memory leaks, and simplifies development by allowing programmers to focus on application logic rather than memory management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Garbage Collection in Java (1)

Garbage collection in Java is an automatic memory management process that identifies and removes unused objects from the heap to free up memory, unlike manual memory management in C/C++. It operates through minor and major garbage collection activities, with the garbage collector running as a background daemon thread. The process enhances memory efficiency, prevents memory leaks, and simplifies development by allowing programmers to focus on application logic rather than memory management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

1

Garbage Collection in Java


Garbage collection in Java is an automatic memory management
process that helps Java programs run efficiently. Java programs
compile to bytecode that can be run on a Java Virtual Machine
(JVM). When Java programs run on the JVM, objects in the heap,
which is a portion of memory dedicated to the program. Eventually,
some objects will no longer be needed. The garbage collector finds
these unused objects and deletes them to free up memory.
In C/C++, programmers have to manually create and delete objects,
which can sometimes lead to memory leaks and errors when there
isn’t enough memory available. This happens when unused objects
are not deleted properly.
In Java, this process is automated. The garbage collector
automatically finds and removes objects that are no longer needed,
freeing up memory in the heap. It runs in the background as a
daemon thread, helping to manage memory efficiently without
requiring the programmer’s constant attention.
Working of Garbage Collection
 Java garbage collection is an automatic process that manages
memory in the heap.
 It identifies which objects are still in use (referenced) and which
are not in use (unreferenced).
 Unreferenced objects can be deleted to free up memory.
 The programmer does not need to mark objects to be deleted
explicitly. The garbage collection implementation lives in the
JVM.
Types of Activities in Java Garbage Collection
Two types of garbage collection activity usually happen in Java.
These are:

1
2

Minor or incremental Garbage Collection: This occurs when


unreachable objects in the Young Generation heap memory are
removed.
Major or Full Garbage Collection: This happens when objects that
survived minor garbage collection are removed from the Old
Generation heap memory. It occurs less frequently than minor
garbage collection.
Important Concepts on Garbage Collection
1. Unreachable Objects
An object is said to be unreachable if it doesn’t contain any reference
to it.
Note: Objects which are part of the island of isolation are also
unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in ‘i’
i = null;
// the Integer object is no longer reachable.
Unreachable Objects
2. Eligibility for Garbage Collection
An object is said to be eligible for garbage collection if it is
unreachable. After i = null, integer object 4 in the heap area is
suitable for garbage collection in the above image.

How to Make an Object Eligible for Garbage Collection?


Even though the programmer is not responsible for destroying
useless objects but it is highly recommended to make an object

2
3

unreachable(thus eligible for GC) if it is no longer required. There are


generally four ways to make an object eligible for garbage collection.
Nullifying the reference variable: Set the reference to null.
Re-assigning the reference variable: Assign a new object to the
reference.
An object created inside the method: Objects created within a
method are eligible for garbage collection once the method
completes.
Island of Isolation: Objects that are isolated and not referenced by
any reachable objects.
Ways to Request JVM to Run Garbage Collection
Once an object is eligible for garbage collection, it may not be
destroyed immediately.The garbage collector runs at the JVM’s
discretion, and you cannot predict when it will occur.
We can also request JVM to run Garbage Collector. There are two
ways to do it :
Using System.gc(): This static method requests the JVM to perform
garbage collection.
Using Runtime.getRuntime().gc(): This method also requests
garbage collection through the Runtime class.
Note: There is no guarantee that the garbage collector will run
immediately after these calls.
3. Finalization
Before destroying an object, the garbage collector calls the finalize()
method to perform cleanup activities. The method is defined in the
Object class as follows:
protected void finalize() throws Throwable

3
4

Note: The finalize() method is called by Garbage Collector, not JVM.


The default implementation of finalize() is empty, so overriding it is
recommended for resource cleanup.
The finalize() method is called only once per object.
If an uncaught exception is thrown by the finalize() method, the
exception is ignored, and the finalization of that object terminates.

Advantages of Garbage Collection in Java


The advantages of Garbage Collection in Java are:
It makes java memory-efficient because the garbage collector
removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM), so
we don’t need extra effort.
Real-World Example
Let’s take a real-life example, where we use the concept of the
garbage collector.
Question: Suppose you go for the internship at GeeksForGeeks, and
you were told to write a program to count the number of employees
working in the company(excluding interns). To make this program,
you have to use the concept of a garbage collector.
This is the actual task you were given at the company:
Write a program to create a class called Employee having the
following data members.
1. An ID for storing unique id allocated to every employee.
2. Name of employee.

4
5

3. Age of an employee.
Also, provide the following methods:
A parameterized constructor to initialize name and age. The ID
should be initialized in this constructor.
A method show() to display ID, name, and age.
A method showNextId() to display the ID of the next employee.
Now any beginner, who doesn’t know Garbage Collector in Java will
code like this:
// Java Program to count number of employees working in a
company
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects

public Employee(String name, int age) {


this.name = name;
this.age = age;
this.ID = nextId++;
}
public void show()
{
5
6

System.out.println("Id=" + ID + "\nName=" + name


+ "\nAge=" + age);
}

public void showNextId()


{
System.out.println("Next employee id will be="
+ nextId);
}}
class UseEmployee {
public static void main(String[] args) {

Employee E = new Employee("GFG1", 56);


Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
{ // It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);

6
7

X.show();
Y.show();
X.showNextId();
Y.showNextId();
}
// After countering this brace, X and Y
// will be removed.Therefore,
// now it should show nextId as 4.

// Output of this line


E.showNextId();
// should be 4 but it will give 6 as output.
}}
Output:

Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4

7
8

Next employee id will be=4


Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6
Now to get the correct output:
Now garbage collector will see 2 objects free. Now to decrement
nextId, garbage collector will call method to finalize() only when we
programmers have overridden it in our class. And as mentioned
previously, we have to request garbage collector, and for this, we
have to write the following 3 steps before closing brace of sub-block.
Set references to null(i.e X = Y = null;)
Call, System.gc();
Call, System.runFinalization();
Now the correct code for counting the number of employees
(excluding interns):
// Correct code to count number
// of employees excluding interns.
class Employee {
private int ID;

8
9

private String name;


private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age) {
this.name = name;
this.age = age;
this.ID = nextId++;
}
public void show()
{
System.out.println("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
}
public void showNextId()
{
System.out.println("Next employee id will be="
+ nextId);
}
protected void finalize()
{
--nextId;

9
10

// In this case,
// gc will call finalize()
// for 2 times for 2 objects.
} }
public class UseEmployee {
public static void main(String[] args) {
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
{
// It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
X.show();
Y.show();
X.showNextId();
Y.showNextId();

10
11

X = Y = null;
System.gc();
System.runFinalization();
}
E.showNextId();
}}
Output:
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4 Next employee id will be=4
Next employee id will be=4 Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6

11
12

Next employee id will be=6


Next employee id will be=4

Java Garbage Collection: Basics


What is Garbage Collection in Java?. In Java applications, objects are
stored in a memory area called the “heap”, which is dedicated to
dynamically allocated objects. If left unattended, these objects can
accumulate and deplete the available memory in the heap –
eventually leading to an OutOfMemoryError.
The Java Virtual Machine (JVM) employs an automatic Garbage
Collection (GC) mechanism. This mechanism handles the release of
memory occupied by unused objects and reallocates that memory
space for new objects.
Common Misunderstanding: Garbage Collection in Java is the
automated process of “deleting code“
Garbage collection in Java is the automated process of reclaiming
memory occupied by unused objects, not deleting code.
Get in-depth information on Java Garbage Collection: automated
memory management, heap memory, mark-and-sweep algorithm,
JVM generations, garbage collectors and more.
The Garbage Collection (GC) feature in the Java Virtual Machine
(JVM) is truly remarkable. It automatically identifies and cleans up
unused Java objects without burdening developers with manual
allocation and deallocation of memory.
As an SRE or Java Administrator you need a strong understanding of
the Java Garbage Collection mechanism to ensure optimal
performance and stability of your Java applications. If you are looking
for a basic general overview on the principles of “What is Garbage
12
13

Collection in Programming?” – you may like to start, here: What is


garbage collection (GC) in programming? (techtarget.com).
As an SRE, you may face these Java Garbage Collection (GC)
challenges
The complex nature of the GC and and its myriad options can often
cause performance issues affecting end user experience due to poor
GC tuning:
 Application Pauses: During GC cycles, the application may
experience pauses causing the application to hang or lag.
 Application Crashes: GC may fail to reclaim sufficient memory.
This can cause OutOfMemory errors, leading to application
crashes.
 High CPU Usage: GC can consume a significant amount of CPU
resources, impacting application performance. Answering the
question: “Is it the application code or the JVM GC?” can be
challenging.
 Memory Fragmentation: Repeated allocation and deallocation
of memory can result in memory fragmentation, slowing down
allocation speed and leading to allocation errors.
An application monitoring tool can detect GC issues and answer the
following questions using historical and real-time data:
 Is garbage collection taking too long and adversely affecting
Java application performance?
 How does performance compare across different garbage
collection settings?
 Are JVM restarts occurring unexpectedly?
In this educational post, we will explain what Java Garbage Collection
is, why it is important, and how to make it easy for Java SREs and
administrators to deal with it. In related posts, we will look at how to
13
14

get detailed visibility into your Java memory and GC Java


performance.
Why is Java Garbage Collection Important?
Java Garbage Collection is essential for several reasons:
1. Automation and simplification: Automatic garbage collection
in Java takes the burden off developers. In contrast, languages
like C or C++ require explicit memory allocation and
deallocation, which can be error-prone and lead to crashes if
not handled properly.
2. Increased Developer Productivity: With automatic Java
memory management, developers can focus on writing
application logic, leading to faster development cycles.
3. Preventing OutOfMemoryError: By automatically tracking and
removing unused objects, garbage collection prevents memory-
related errors like OutOfMemoryError errors.
4. Eliminates dangling pointer bugs: These are bugs that occur
when a piece of memory is freed while there are still pointers
to it, and one of those pointers is dereferenced. By then the
memory may have been reassigned to another use with
unpredictable results.
5. Eliminates Double free bugs: These happen when the program
tries to free a region of memory that has already been freed
and perhaps already been allocated again.
Java GC is automatic but is not a silver bullet
1. GC can still impact performance: In spite of its benefits, GC can
still impact application speed. As an SRE, you need to select the
appropriate garbage collector relative to your application
workloads.

14
15

2. GC cannot prevent memory leaks: A memory leak in Java is a


situation where unreferenced objects persist in memory,
preventing the garbage collector from reclaiming them. This
can lead to application slowdowns or crashes.
Application Monitoring: Use application monitoring tools to detect
and address performance issues promptly. This proactive approach
ensures smooth and efficient Java applications.

Memory Heap Generations in Java Garbage Collection


Understanding the memory heap generations is crucial for Java
garbage collection efficiency. The generations are:
1. Eden: Where objects are created; GC removes unused objects
or moves them to Survivor space if still referenced.
2. Survivor: Comprises survivor zero and survivor one spaces in
the young generation.
3. Tenured: Holds long-lived objects; GC checks this less
frequently due to its larger size in the old generation.
Garbage collection occurs more often in Eden, while Tenured is
checked less, optimizing the process. Minor garbage collection takes
place in the young generation, while major garbage collection occurs
in the old generation and takes longer but happens less frequently.
The permanent generation (PermGen) was removed in Java 8.
How does Garbage Collection work in Java? Java Garbage Collection
explained.
In Java, objects are created dynamically using the “new” keyword.
Once an object is created, it occupies memory space on the heap. As
a program executes, objects that are no longer referenced or
accessible need to be removed to free up memory and prevent
memory leaks. Thus, the Java heap memory contains a collection of

15
16

live and dead objects – live objects are still in use and dead objects
are no longer needed.
The Garbage Collection in Java operation is based on the premise
that most objects used in the Java code are short-lived and can be
reclaimed shortly after their creation. As a result of garbage
collection in Java, unreferenced objects are automatically removed
from the heap memory, which makes Java memory-efficient.
In general, all Java garbage collectors have two main objectives:
1. Identify all objects that are still in use or “alive.”.
2. Remove all other objects that are considered dead or unused
(i.e., unreachable).
The Java garbage collector performs this task by periodically
identifying and reclaiming memory that is no longer in use. The most
commonly used Java Garbage Collection algorithm is called the mark-
and-sweep algorithm, which follows these steps:

16
17


Marking phase: The garbage collector starts with a root set of
objects (e.g., global variables, stack frames, and CPU registers)
that are known to be in use. It recursively traverses through
these objects, marking each object it encounters as “live” or
reachable. All reachable objects starting from known root
references (such as local variables, static variables, and thread
stacks) are marked as live objects.
 Sweeping phase: The garbage collector scans the entire heap,
identifying and reclaiming memory occupied by objects that
were not marked during the marking phase. These objects are
considered garbage. Any objects that have not been marked as
“live” during the mark phase are considered unreachable and
are marked as eligible for garbage collection. The memory
occupied by these unreachable objects is then freed up for
future allocations.
When is an Object eligible for Garbage Collection?

17
18

 Every Java program has one or more threads. An object is


eligible for garbage collection when no live thread can access it.
 If two objects have reference to each other and do not have
any live reference then both objects are candidates for being
garbage collected.
 If a reference of an object is explicitly set to null, the object is
available for garbage collection.
 An object also becomes eligible for garbage collection if it is
created inside a block and the reference goes out of the scope
once control of the program exits from this block.
Objects that are actively referenced by live threads are not eligible
for garbage collection.
Two types of garbage collection activity that usually happen in Java
 A minor or incremental Java garbage collection is said to have
occurred when unreachable objects in the young generation
heap memory are removed.
 A major or full Java garbage collection is said to have occurred
when the objects that survived the minor garbage collection
and were then copied into the old generation or permanent
generation heap memory are removed. When compared to
young generation, garbage collection happens less frequently
in old generation.
To free up memory, the JVM must stop the application from running
for at least a short time and execute the GC process. This process is
called “stop-the-world.” This means all the threads, except for the
GC threads, will stop executing until the GC threads are executed and
objects are freed up by the garbage collector.
Modern Java GC implementations try to minimize blocking “stop-the-
world” stalls by doing as much work as possible in the background

18
19

(i.e. using a separate thread), for example marking unreachable


garbage instances while the application process continues to run.
Java Garbage Collection – Impact on Performance
Garbage collection in the JVM consumes CPU resources when
deciding which memory to free. Stopping the program or consuming
high levels of CPU resources will have a negative impact on the end-
user experience with users complaining that the application is slow.
Various Java garbage collectors have been developed over time to
reduce the application pauses that occur during garbage collection
and at the same time to improve on the performance hit associated
with garbage collection.
Modern JVMs have multiple collectors (alternative garbage collection
algorithms) for performing the GC activity:
 Serial Garbage Collector: Single-threaded GC execution. Enable
with -XX:+UseSerialGC.
 Parallel Garbage Collector: Multiple minor threads executing
GC in parallel. Enable with -XX:+UseParallelGC.
 Concurrent Mark Sweep (CMS): Concurrent execution of some
application threads with reduced stop-the-world GC frequency.
Enable with -XX:+UseConcMarkSweepGC. However, note that
CMS was deprecated in JDK 9.
 G1 Garbage Collector: Designed for big workloads, concurrent,
minimizes pauses, adapts to machine conditions, string de-
duplication feature reduces the overhead of strings. You can
explicitly enable it using the JVM option -XX:+UseG1GC.
 Epsilon Garbage Collector: Do-nothing GC for ultra-latency-
sensitive or garbage-free applications. Use the following flags: -
XX:+UnlockExperimentalVMOptions and -XX:+UseEpsilonGC

19
20

 Shenandoah Garbage Collector: Concurrent GC with


compaction and memory release while the application is
running. Use the following flags: -XX:+UseShenandoahGC -
XX:+UnlockExperimentalVMOptions -
XX:ShenandoahGCMode=generational
 ZGC (Z Garbage Collector): Experimental initially, designed for
large heaps, concurrent, low pause times (<10ms), supports
small to massive heap sizes. ZGC can be enabled using the -
XX:+UseZGC JVM option.
Many JVMs, such as Oracle HotSpot, JRockit, OpenJDK, IBM J9, and
SAP JVM, use stop-the-world GC techniques – however, recent
collectors such as G1GC and ZGC are changing this situation. Modern
JVMs like Azul Platform Prime (formerly Zing) use Continuously
Concurrent Compacting Collector (C4), which eliminates the stop-
the-world GC pauses that limit scalability in the case of conventional
JVMs.
Why is Monitoring Java Garbage Collection Important?
Garbage collection can impact the performance of Java applications
in unpredictable ways. When there is frequent GC activity, it adds a
lot of CPU load and slows down application processing. In turn, this
leads to slow execution of business transactions and ultimately
affects the user experience of end-users accessing the Java
application.
Excessive garbage collection activity can occur due to a memory leak
in the Java application. Insufficient memory allocation to the JVM can
also result in increased garbage collection activity. And when
excessive garbage collection activity happens, it often manifests as
increased CPU usage of the JVM!
For optimal Java application performance, it is critical to monitor a
JVM’s GC activity. For good performance, full GCs should be few and

20
21

far between. The time spent on GC should be low – typically less


than 5% and the percentage of CPU spent for garbage collection
should also be very low (this allows application threads to use almost
all the available CPU resources).
What are the Key Java Garbage Collection Metrics to Monitor?
To know if garbage collection is creating Java performance
problems, you need to track all aspects of the garbage collection
activity in the JVM:
 When garbage collection happened
 How often garbage collection is happening in the JVM
 How much memory is being collected each time
 How long garbage collection is running for in the JVM
 Percentage of time spent by JVM for garbage collection
 What type of garbage collection happened – minor or full GC?
 JVM heap and non-heap memory usage
 CPU utilization of the JVM
This allows you to identify when Java garbage collection is taking too
long and impacting performance, which will help you to determine
the optimal settings for each application based on historical patterns
and trends.
Troubleshooting Java Garbage Collection Issues
One way to troubleshoot whether the Java garbage collection
process is impacting the performance of your application, when Java
GC activity is excessive, is to take heap dumps of the JVM’s memory
and analyze the top memory consuming objects. Any unusually large
objects are an indicator of memory leaks in the application code.

21
22

On the other hand, if no object is occupying an unusually large


amount of memory and if the percentage of memory used by any of
the JVM’s memory pools is close to 100%, this is an indicator that the
JVM’s memory configuration may be insufficient. In this case, you
may need to increase the corresponding JVM memory pool for
improved application performance.
Conclusion
Now that we have fair understanding of Java garbage collection, let’s
summarize by answering some of key questions SREs and Java
admins may have:
 Is garbage collection in Java good or bad? Definitely good. But,
as the adage goes, too much of anything is a bad thing. So, you
need to make sure Java heap memory is properly configured
and managed so that the GC activity is optimized.
 When is Java GC needed? It is needed when there are
unreferenced objects to be cleared out. Since it is not a manual
activity, the JVM will automatically take care of this for you.
From all the information above, you would have learned why
GC is needed and when.
 How to tune Java garbage collection? There are two common
ways to do this:
1. Keep the number of objects passed to the old generation
area to a minimum
2. Configure the major (or full) GC time to be low
 Some critical JVM parameters to configure for right-sizing the
JVM’s memory are -Xms, -Xmx, and -NewRatio (ratio of new
generation and old generation size)

22
23

 How to know when Java GC is not operating as expected? JVM


monitoring is key. Make sure to track vital JVM metrics and be
alerted when GC activity is deviating from the norm.
What is Garbage Collection in Java?
Garbage collection in Java is a built-in process that automatically
cleans up memory by removing objects your program no longer
needs. Unlike languages like C++, where developers have to manually
free up memory, Java handles this process for you. This helps your
application run efficiently. The Java Virtual Machine (JVM) handles
this process. It tracks the objects you create and determines which
ones are no longer in use. When an object is no longer needed, the
JVM removes it to prevent issues like memory leaks.
Memory leaks happen when memory is occupied by objects that are
no longer in use but aren’t released. In Java, memory is organized
into a space called the heap, which is divided into sections.
 The Young Generation is where new objects are created
 The Old Generation is for objects that have been around
longer,
 Older Java versions also had a Permanent Generation for
metadata (now replaced by Metaspace in newer versions).
The garbage collector periodically checks which objects are still being
used by your program.
What is the Java Heap Memory in Garbage Collection?
Let’s understand some terms first. The Java heap or Java heap
memory – you will come across this term many times throughout
this article – is where objects are stored. It’s an important part of
memory management. The JVM further divides it into three main
sections to manage objects effectively: young generation, old

23
24

generation, and permanent generation which we have talked about


earlier.
Heap Structure Explained
The Java heap is divided into different sections to manage memory
effectively: the Young Generation, the Old Generation, and (in older
Java versions) the Permanent Generation. Here's how they work in
simple terms:
 Young Generation: This is where new objects are created. It’s
the busiest part of the heap because most objects are short-
lived and quickly discarded. Garbage collection happens
frequently here to clean up memory and make space for new
objects. It’s further divided into three smaller regions:
o Eden: Where all new objects start.
o Survivor Space 1 and Survivor Space 2: Where objects
that survive the first round of garbage collection are
temporarily stored. Most objects in this area are short-
lived, so they’re cleared quickly during garbage collection.
 Old Generation: Objects that survive several rounds of garbage
collection in the Young Generation are moved here. These are
the long-lived objects your program continues to use. Garbage
collection happens less often here, but it’s more thorough since
this section holds more data.
 Permanent Generation: In older Java versions, this part stored
metadata like class and method information needed by the
JVM. However, it has been replaced by Metaspace in modern
Java versions. Metaspace is more efficient because it adjusts
dynamically to the memory needs of your program, especially
useful for applications with varying workloads.
Now that you know where the garbage collection process happens,
it’s time to understand what operations occur there.
24
25

Basic Operations: Marking, Deletion, and Compaction


The three basic operations in the heart of garbage collection are
marking, deletion, and compaction. In marking, objects still in use are
identified so they can remain. This is the critical part that prevents
accidentally deleting the active objects.
Deletion is the removal of objects that are no longer referenced. Via
this step, the garbage collector reclaims memory. The final operation
of compaction moves reachable objects closer together. This reduces
fragmentation while improving the efficiency of memory allocations.
'Stop-the-World' Events
A Stop-the-World (STW) event in garbage collection is when the
application temporarily pauses so the garbage collector can clean up
unused memory. During this time, everything in the program
stops—no tasks or threads run until the garbage collection is
complete.
These pauses are necessary, but they can slow down your
application, especially if they last too long. This can be a problem for
apps that need to respond quickly, like real-time or interactive
applications.
To keep applications running smoothly, it’s important to use garbage
collection algorithms that minimize these pauses as much as
possible. Shorter STW events mean a more responsive and user-
friendly application.
As we mentioned earlier, the garbage collector as a per-defined set
of rules, also called an algorithm. A developer can instruct JVM what
and what-not to perform during garbage collection. It is one of the
most crucial parts of this process. There are some common
algorithms that you should know to understand their impact and
make this process more effective further. These algorithms

25
26

determine the efficiency of garbage collection processes, from


simple short-lived objects to rather complex long-lived objects.
Common Garbage Collection Algorithms
There are several such garbage collection algorithms present in Java,
each with its strengths. Here is a simple breakdown of how they
work:
 Mark-Sweep: This algorithm "marks" all the objects still in use
(live objects) and then "sweeps" through memory to clear out
those no longer needed (garbage). It is simple but causes
fragmentation because live objects can end up scattered across
memory, leaving gaps.
 Copying Collector: The algorithm divides the memory into two
halves. It moves live objects from one half to another, which
aids in compacting memory and thus reducing fragmentation
since the live objects reside together in one place.
 Mark-Compact: This is the combination of both Mark-Sweep
and Copying. It marks the live objects and compacts them, thus
avoiding fragmentation without requiring extra memory space.
 Generational Garbage Collection: This approach divides objects
into generations based on their age. It focuses more upon
collecting the young objects, which are most likely discarded
making garbage collection faster and more effective.
Each algorithm works better in different situations, depending on the
needs of the application. The Java garbage collector can adapt to use
the best method for a given scenario, balancing performance and
memory management.

Generational Garbage Collection: A More Advanced Technique

26
27

Generational Garbage Collection organizes objects into different


"generations" based on their age. This makes it easier to manage
memory for objects that are more likely to be removed.
The idea is that most objects in a program are short-lived, so the
garbage collector focuses on cleaning up these short-lived objects
first. There are two types of garbage collection in this system:
 Minor Garbage Collection: This happens often and focuses on
cleaning the Young Generation, where most of the objects are
short-lived.
 Major Garbage Collection: This is less frequent but more
intensive, as it cleans the Old Generation, which has long-lived
objects.
Generational garbage collection is very efficient because it takes
advantage of how long objects live in a program. This system works
particularly well for applications that create and destroy a lot of
objects frequently, like web servers that handle short requests. This
is also great for real-time applications, where it’s important to
minimize delays.
While this method is well-suited for many types of applications,
some apps may need adjustments to memory management based on
their specific needs.
How to Monitor and Optimize Garbage Collection
You can monitor this process, and even though the mechanism is
advanced, human intervention is always required instead of entirely
depending on rule-based algorithms.
To keep Java applications running smoothly, it’s important to
regularly monitor how garbage collection is working. Moreover, Java
offers tools to monitor garbage collection. Some tools provide real-
time data, while others create detailed reports.

27
28

Tools for Monitoring Garbage Collection


There are several tools in Java that help monitor garbage collection
and track how well your application is performing.
 VisualVM is quite a powerful tool that brings real-time
monitoring and analysis on board. It gives the user an accurate
view of their memory usage and garbage collection activities. It,
therefore helps understand the application's actual running
situation and where amendments can be made.
 Another tool included in the JDK is JConsole. It has a very
simple interface for monitoring memory usage, thread activity,
and garbage collection events. It is very useful for developers
who need quick snapshots of performance.
 The garbage collection logs is also the way of monitoring,
although this is very less manual. Logs can be activated with
Java command line option. These logs will include complete
information regarding the event that occurred due to garbage
collection. It helps fine-tune the performance patterns as well
as trends to make it even more finer-tuned.
Conclusion
¿

28

You might also like