Importance of destroyForcibly() method in Java 9?

The destroyForcibly() method can be used to kill a process. It will be needed if the process has finished or has frozen. For instance, the isAlive() method returns true after destroyForcibly() is called. The destroyForcibly() method returns true if the termination successfully requested, otherwise returns false.

Syntax

<strong>boolean destroyForcibly()</strong>

In the below example, we will able to launch a notepad application, and it will be terminated after the destroyForcibly() method called.

Example

import java.io.IOException;
import java.lang.ProcessBuilder;

public class DestroyForciblyTest {
   public static void main(String args[]) throws IOException, InterruptedException {
      <strong>ProcessBuilder </strong>pBuilder = new <strong>ProcessBuilder()</strong>;
      pBuilder.<strong>command</strong>("notepad.exe");

      <strong>// Start notepad application</strong>
      Process process = pBuilder.<strong>start()</strong>;
      System.out.println("Started Notepad Application");

      <strong>// Sleep for 5 seconds</strong>
      Thread.sleep(5000);

      <strong>// Kill the notepad</strong>
      process.<strong>destroyForcibly()</strong>;
      System.out.println("End of Notepad Application");
   }
}



Output

<strong>Started Notepad Application
End of Notepad Application</strong>
Updated on: 2020-04-30T17:21:25+05:30

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements