java finalizers,如果Java finalize方法中存在无限循环或死锁,Finalizer线程将执行什么操作...

what will the Finalizer thread do if there is a infinite loop or deadlock in the Java finalize method.

解决方案

The spec writes:

Before the storage for an object is reclaimed by the garbage collector, the Java Virtual Machine will invoke the finalizer of that object.

The Java programming language does not specify how soon a finalizer will be invoked, except to say that it will happen before the storage for the object is reused.

I read this to mean that the finalizer must have completed before the storage may be reused.

The Java programming language does not specify which thread will invoke the finalizer for any given object.

It is important to note that many finalizer threads may be active (this is sometimes needed on large shared memory multiprocessors), and that if a large connected data structure becomes garbage, all of the finalize methods for every object in that data structure could be invoked at the same time, each finalizer invocation running in a different thread.

That is, finalization may occur in the garbage collector thread, in a separate thead, or even a separate thread pool.

A JVM is not permitted to simply abort executing a finalizer, and can only use a finite number of threads (threads are operating system resources, and operating systems don't support arbitrarily many threads). Non-terminating finalizers will therefore of necessity starve that thread pool, thereby inhibit collection of any finalizable objects, and cause a memory leak.

The following test program confirms this behavior:

public class Test {

byte[] memoryHog = new byte[1024 * 1024];

@Override

protected void finalize() throws Throwable {

System.out.println("Finalizing " + this + " in thread " + Thread.currentThread());

for (;;);

}

public static void main(String[] args) {

for (int i = 0; i < 1000; i++) {

new Test();

}

}

}

On Oracle JDK 7, this prints:

Finalizing tools.Test@1f1fba0 in thread Thread[Finalizer,8,system]

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

at tools.Test.(Test.java:5)

at tools.Test.main(Test.java:15)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值