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:


public class Execute {
    public static void main(String[] args) {
        String s = new Execute().executeCommand("netstat -tulpn", "");
        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);

        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);
            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) {

        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*               LISTEN      11681/java          

frances+ 11681 11638  7 12:36 pts/3    00:00:50 java -D[Standalone] -server -Xms64m -Xmx512m -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=256m -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/ -jar /home/francesco/jboss/wildfly-14.0.0.Final/jboss-modules.jar -mp /home/francesco/jboss/wildfly-14.0.0.Final/modules -Djboss.home.dir=/home/francesco/jboss/wildfly-14.0.0.Final -Djboss.server.base.dir=/home/francesco/jboss/wildfly-14.0.0.Final/standalone