How to kill a Java process from Java

Today I had to write a quick code to find out which Java process is using a Port and eventually killed it. You can use it as template in case you have to manage OS process in Linux from Java code:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Execute {
    public static void main(String[] args) {
        String s = new Execute().executeCommand("netstat -tulpn", "127.0.0.1:8080");
        System.out.println(s);
        int left = s.indexOf("LISTEN");
        int right = s.indexOf("/java");
        String process = s.substring(left + 6, right).trim();

        String sp = new Execute().executeCommand("ps -ef", process);
        System.out.println(sp);

        String spkill = new Execute().executeCommand("kill -9 " + i, process);
    }

    private String executeCommand(String command, String grep) {

        StringBuffer output = new StringBuffer();

        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                if (line.indexOf(grep) > 1)
                    output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();

    }

}

Just a note, as Unix’s pipes (“|”) won’t work if you add them in a single String passed to the Runtime object, I have used a simple strategy to filter the output of commands. I’m passing the String to be filtered as argument to the executeCommand method. Not sure if it’s the best way to do it but it works pretty well!

Sample output:

tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      11681/java          

11681
frances+ 11681 11638  7 12:36 pts/3    00:00:50 java -D[Standalone] -server -Xms64m -Xmx512m -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true -Dorg.jboss.boot.log.file=/home/francesco/jboss/wildfly-14.0.0.Final/standalone/log/server.log -Dlogging.configuration=file:/home/francesco/jboss/wildfly-14.0.0.Final/standalone/configuration/logging.properties -jar /home/francesco/jboss/wildfly-14.0.0.Final/jboss-modules.jar -mp /home/francesco/jboss/wildfly-14.0.0.Final/modules org.jboss.as.standalone -Djboss.home.dir=/home/francesco/jboss/wildfly-14.0.0.Final -Djboss.server.base.dir=/home/francesco/jboss/wildfly-14.0.0.Final/standalone
Found the article helpful? if so please follow us on Socials