通常在普通的 Java 程序中你不会遇到这个问题。
但是是的,如果你使用像sun.misc.Unsafe 这样的东西,你可能会导致分段错误。但这就是为什么Unsafe 被称为Unsafe。通常您不必使用它,因此您的代码中不会出现此问题。
更多信息:
Where is sun.misc.Unsafe documented?
基于sun.misc.Unsafe 的分段错误报告的错误
https://github.com/eclipse/openj9/issues/4153
这里有一个如何测试的例子:
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class MainClass {
public static void main(String[] args)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
long ten = 10;
byte size = 1;
long mem = unsafe.allocateMemory(size);
//Put here the wrong address!!!
unsafe.putAddress(1, ten);
//With this will work:
//unsafe.putAddress(mem, ten);
long readValue = unsafe.getAddress(mem);
System.out.println("result: " + readValue);
}
}
当我在 Ubuntu 18.04 上执行时,我得到以下输出:
A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x00007f05bdf04d27, pid=4145, tid=4147
JRE version: OpenJDK Runtime Environment (10.0.2+13) (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
在 Windows 上,我认为这将是带有致命错误描述的类似输出。
祝大家好运!