如果Java finalize方法中存在无限循环或死锁,Finalizer线程将执行什么操作 [英] what will the Finalizer thread do if there is a infinite loop or deadlock in the Java finalize method

查看:366
本文介绍了如果Java finalize方法中存在无限循环或死锁,Finalizer线程将执行什么操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 Java finalize方法中存在无限循环或死锁,那么终结器线程会怎样做。

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

推荐答案

规范写道:


在存储之前对象由垃圾回收器回收,Java虚拟机将调用该对象的终结器。

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

Java编程语言没有指定调整终结器的时间,除了说它会在重复使用对象的存储之前发生。

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.


Java编程语言没有指定哪个线程将为任何给定对象调用终结器。

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

重要的是要注意许多终结器线程可能是活动的(有时在大型共享内存多处理器上需要),如果是大型连接数据结构变为垃圾,可以同时调用该数据结构中每个对象的所有finalize方法,每个终结器调用在不同的线程中运行。

也就是说,最终化可能发生在垃圾收集器线程中,单独的thead中,甚至是单独的线程池中。

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

JVM不允许简单地中止执行终结器,并且只能使用有限数量的线程(线程是操作系统资源,操作系统不支持任意多个线程)。因此,非终止终结器必然会占用该线程池,从而禁止收集任何可终结对象,并导致内存泄漏。

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();
        }
    }
}

在Oracle JDK 7上,这个打印:

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.<init>(Test.java:5)
        at tools.Test.main(Test.java:15)


这篇关于如果Java finalize方法中存在无限循环或死锁,Finalizer线程将执行什么操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆