从未通过 allocateInstance(Java) 从对象调用 finalize
finalize never called from the object by allocateInstance(Java)
请参考以下代码,我只是想做一些关于不安全的事情。
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);
}
}
代码永远不会oom,但是class B的finalize永远不会called.why?
我找不到关键信息....
This OpenJDK thread 注释如下:
Unsafe.allocateInstance() is implemented in HotSpot VM by directly calling JNI's AllocObject()
function [1].
An object instance is allocated in the Java heap, but no constructors are invoked for this instance.
此外,Java Langauge Specification (§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).
鉴于在您的代码中您从未真正为分配的实例调用构造函数,因此如果不首先违反上述 happens-before order (§17.4.5).
就无法调用 Object.finalize()
方法
因此,Object.finalize()
方法永远不会被调用。
请参考以下代码,我只是想做一些关于不安全的事情。
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);
}
}
代码永远不会oom,但是class B的finalize永远不会called.why? 我找不到关键信息....
This OpenJDK thread 注释如下:
Unsafe.allocateInstance() is implemented in HotSpot VM by directly calling JNI's
AllocObject()
function [1]. An object instance is allocated in the Java heap, but no constructors are invoked for this instance.
此外,Java Langauge Specification (§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).
鉴于在您的代码中您从未真正为分配的实例调用构造函数,因此如果不首先违反上述 happens-before order (§17.4.5).
就无法调用Object.finalize()
方法
因此,Object.finalize()
方法永远不会被调用。