java-9processhandle

How to kill the current process with java 9


I have tried with both destroy and destroyForcibly using the below code -

ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("current process id:"+currentProcess.getPid());
currentProcess.destroyForcibly();

but getting an exception in both cases as

Exception in thread "main" java.lang.IllegalStateException: destroy of current process not allowed at java.base/java.lang.ProcessHandleImpl.destroyProcess(ProcessHandleImpl.java:308) at java.base/java.lang.ProcessHandleImpl.destroyForcibly(ProcessHandleImpl.java:331) at util.CurrentProcess.main(CurrentProcess.java:18)


Solution

  • Javadoc on ProcessHandle::current says:

    Returns a ProcessHandle for the current process. The ProcessHandle cannot be used to destroy the current process, use System.exit instead.