How Java Garbage Collection Works

How Java Garbage Collection Works?

This tutorial is to understand the basics of Java garbage collection and how it works. 

This is the second part in the garbage collection tutorial series. 

Hope you have read  introduction to Java garbage collection, which is the first part.

Java garbage collection is an automatic process to manage the runtime memory used by programs. 

By doing it automatic JVM relieves the programmer of the overhead of assigning and freeing up memory resources in a program.

Java Garbage Collection GC Initiation

Being an automatic process, programmers need not initiate the garbage collection process explicitly in the code.  System.gc() and Runtime.gc() are hooks to request the JVM to initiate the garbage collection process.

Though this request mechanism provides an opportunity for the programmer to initiate the process but the onus is on the JVM. 

It can choose to reject the request and so it is not guaranteed that these calls will do the garbage collection. 

This decision is taken by the JVM based on the eden space availability in heap memory. 

The JVM specification leaves this choice to the implementation and so these details are implementation specific.

Undoubtedly we know that the garbage collection process cannot be forced. 

I just found out a scenario when invoking System.gc() makes sense. 

Just go through this article to know about this corner case when System.gc() invocation is applicable.


Java Garbage Collection Process

Garbage collection is the process of reclaiming the unused memory space and making it available for the future instances.

Java-Garbage-Collection-Process[3]

Eden Space: When an instance is created, it is first stored in the eden space in young generation of heap memory area.

NOTE: If you couldn’t understand any of these words, 

I recommend you to go through the garbage collection introduction tutorial which goes through the memory mode, 

JVM architecture and these terminologies in detail.

Survivor Space (S0 and S1): As part of the minor garbage collection cycle, 

objects that are live (which is still referenced) are moved to survivor space S0 from eden space. 

Similarly the garbage collector scans S0 and moves the live instances to S1.

Instances that are not live (dereferenced) are marked for garbage collection. 

Depending on the garbage collector (there are four types of garbage collectors available and we will see about them in the next tutorial) chosen either the marked instances will be removed from memory on the go or the eviction process will be done in a separate process.

Old Generation: Old or tenured generation is the second logical part of the heap memory. 

When the garbage collector does the minor GC cycle, instances that are still live in the S1 survivor space will be promoted to the old generation. Objects that are dereferenced in the S1 space is marked for eviction.

Major GC: Old generation is the last phase in the instance life cycle with respect to the Java garbage collection process. Major GC is the garbage collection process that scans the old generation part of the heap memory. If instances are dereferenced, then they are marked for eviction and if not they just continue to stay in the old generation.

Memory Fragmentation: Once the instances are deleted from the heap memory the location becomes empty and becomes available for future allocation of live instances. 

These empty spaces will be fragmented across the memory area. For quicker allocation of the instance it should be defragmented. 

Based on the choice of the garbage collector, the reclaimed memory area will either be compacted on the go or will be done in a separate pass of the GC.

Finalization of Instances in Garbage Collection

Just before evicting an instance and reclaiming the memory space, the Java garbage collector invokes the finalize() method of the respective instance so that the instance will get a chance to free up any resources held by it. 

Though there is a guarantee that the finalize() will be invoked before reclaiming the memory space, there is no order or time specified. 

The order between multiple instances cannot be predetermined, they can even happen in parallel. 

Programs should not pre-mediate an order between instances and reclaim resources using the finalize() method.

  • Any uncaught exception thrown during finalize process is ignored silently and the finalization of that instance is cancelled.
  • JVM specification does not discuss about garbage collection with respect to weak references and claims explicitly about it. Details are left to the implementer.
  • Garbage collection is done by a daemon thread.

When an object becomes eligible for garbage collection?

  • Any instances that cannot be reached by a live thread.
  • Circularly referenced instances that cannot be reached by any other instances.

There are different types of references in Java. Instances eligibility for garbage collection depends on the type of reference it has.

ReferenceGarbage Collection
Strong ReferenceNot eligible for garbage collection
Soft ReferenceGarbage collection possible but will be done as a last option
Weak ReferenceEligible for Garbage Collection
Phantom ReferenceEligible for Garbage Collection

During compilation process as an optimization technique the Java compiler can choose to assign null value to an instance, 

so that it marks that instance can be evicted.

class Animal {
    public static void main(String[] args) {
        Animal lion = new Animal();
        System.out.println("Main is completed.");
    }

    protected void finalize() {
        System.out.println("Rest in Peace!");
    }
}

In the above class, lion instance is never uses beyond the instantiation line. 

So the Java compiler as an optimzation measure can assign lion = nulljust after the instantiation line. 

So, even before SOP’s output, the finalizer can print ‘Rest in Peace!’. 

We cannot prove this deterministically as it depends on the JVM implementation and memory used at runtime. 

But there is one learning, compiler can choose to free instances earlier in a program if it sees that it is referenced no more in the future.

  • One more excellent example for when an instance can become eligible for garbage collection. All the properties of an instance can be stored in the register and thereafter the registers will be accessed to read the values. There is no case in future that the values will be written back to the instance. Though the values can be used in future, still this instance can be marked eligible for garbage collection. Classic isn’t it?
  • It can get as simple as an instance is eligible for garbage collection when null is assigned to it or it can get complex as the above point. These are choices made by the JVM implementer. Objective is to leave as small footprint as possible, improves the responsiveness and increase the throughput. In order to achieve this the JVM implementer can choose a better scheme or algorithm to reclaim the memory space during garbage collection.
  • When the finalize() is invoked, the JVM releases all synchronize locks on that thread.

Example Program for GC Scope

Class GCScope {
	GCScope t;
	static int i = 1;

	public static void main(String args[]) {
		GCScope t1 = new GCScope();
		GCScope t2 = new GCScope();
		GCScope t3 = new GCScope();

		// No Object Is Eligible for GC

		t1.t = t2; // No Object Is Eligible for GC
		t2.t = t3; // No Object Is Eligible for GC
		t3.t = t1; // No Object Is Eligible for GC

		t1 = null;
		// No Object Is Eligible for GC (t3.t still has a reference to t1)

		t2 = null;
		// No Object Is Eligible for GC (t3.t.t still has a reference to t2)

		t3 = null;
		// All the 3 Object Is Eligible for GC (None of them have a reference.
		// only the variable t of the objects are referring each other in a
		// rounded fashion forming the Island of objects with out any external
		// reference)
	}

	protected void finalize() {
		System.out.println("Garbage collected from object" + i);
		i++;
	}

Example Program for GC OutOfMemoryError

Garbage collection does not guarantee safety from out of memory issues. Mindless code will lead us to OutOfMemoryError.

import java.util.LinkedList;
import java.util.List;

public class GC {
	public static void main(String[] main) {
		List l = new LinkedList();
		// Enter infinite loop which will add a String to the list: l on each
		// iteration.
		do {
			l.add(new String("Hello, World"));
		} while (true);
	}
}

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.LinkedList.linkLast(LinkedList.java:142)
	at java.util.LinkedList.add(LinkedList.java:338)
	at com.javapapers.java.GCScope.main(GCScope.java:12)

Next is the third part of the garbage collection tutorial series and we will see about the different types of Java garbage collectors available.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了小程序应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值