As far as I understand by using System.exit()
application shuts down grafecully. But I want a abnormal shut down.
How can I achieve this with java code?
As far as I understand by using System.exit()
application shuts down grafecully. But I want a abnormal shut down.
How can I achieve this with java code?
The System.exit()
method takes a status code parameter. A non-zero value status code is used for abnormal termination.
What you want to achieve can be done with System.exit(1)
.
You could search for bugs that crash the JVM and aren't fixed. For example I found this "user error" bug https://bugs.openjdk.java.net/browse/JDK-8225643 and it works (i.e. crashes) in my case (openjdk 11.0.9 2020-10-20).
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public final class Temp {
public static void main(String... args) throws Exception {
int a = 5;
int b = 10;
System.out.printf("a: %s, b: %s\n", a, b);
swap(addressOf(a), addressOf(b), Integer.BYTES);
System.out.printf("a: %s, b: %s\n", a, b);
}
@SuppressWarnings("unchecked")
public static <T> long addressOf(T t) throws NoSuchFieldException, IllegalAccessException {
T[] arr = (T[])new Object[]{t};
Unsafe unsafe = getUnsafe();
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
int addressSize = unsafe.addressSize();
long objectAddress;
switch (addressSize) {
case 4:
objectAddress = unsafe.getInt(arr, baseOffset);
break;
case 8:
objectAddress = unsafe.getLong(arr, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}
return (objectAddress);
}
public static void swap(long addr_1, long addr_2, long bytes) throws NoSuchFieldException, IllegalAccessException {
Unsafe unsafe = getUnsafe();
if (unsafe == null) {
System.out.println("Cannot swap variables!");
return;
}
long allocateMemory_var1 = unsafe.allocateMemory(bytes);
unsafe.copyMemory(addr_1, allocateMemory_var1, bytes);
unsafe.copyMemory(addr_2, addr_1, bytes);
unsafe.copyMemory(allocateMemory_var1, addr_2, bytes);
}
private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe)f.get(null);
}
}
(I don't know why the code is that long; I just copied it from the bug report and made it compile-able)