[英]finalize never called from the object by allocateInstance(Java)
pleaes refer to the following code, i just want to do something about unsafe. 请参考下面的代码,我只想对不安全做一些事情。
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe u = (Unsafe) f.get(null);
System.out.println("the while start at:" + new Date());
long total = 0;
while (true) {
u.allocateInstance(B.class);
total++;
if (total % 100000000 == 0) {
System.out.println(total);
System.gc();
}
}
}
}
class B {
private int a;
private int b;
private double d;
private float e;
@Override
protected void finalize() {
try {
super.finalize();
} catch (Throwable e) {
System.out.println("catch excep");
}
System.out.println("class B finalize, the a:" + a);
}
}
the code is never oom, but the finalize of class B is never called.why? 代码永远不会是oom,但是永远不会调用B类的终结函数。为什么? i can not find the key information....
我找不到关键信息。
This OpenJDK thread notes the following: 此OpenJDK线程注意以下内容:
Unsafe.allocateInstance() is implemented in HotSpot VM by directly calling JNI's
AllocObject()
function [1] .通过直接调用JNI的
AllocObject()
函数[1]在HotSpot VM中实现AllocObject()
。 An object instance is allocated in the Java heap, but no constructors are invoked for this instance.对象实例在Java堆中分配,但是没有为该实例调用构造函数。
Furthermore, the Java Langauge Specification (§12.6.0) specifically states that: 此外, Java语言规范(§12.6.0)特别声明:
The completion of an object's constructor happens-before ( §17.4.5 ) the execution of its finalize method (in the formal sense of happens-before).
对象的构造函数的完成发生在第( §17.4.5节 )其finalize方法的执行之前(从正式意义上来说,发生在before之前)。
Given that in your code you never actually call the constructors for the allocated instances, the Object.finalize()
method cannot be called without first violating the aforementioned happens-before order (§17.4.5) . 鉴于在您的代码中您实际上从未真正调用过分配实例的构造函数,因此,必须先违反上述先发生后顺序(§17.4.5)才能调用
Object.finalize()
方法。
Therefore, the Object.finalize()
method will never be called. 因此,将永远不会调用
Object.finalize()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.