0

I have implemented a way to timeout my process running iperf server side based on this question's top answear and it works as intended but I am not sure how to destroy a process object that I pass inside Task's class constructor.
This is my modified code:

public class Main {

    public static void main(String[] args) throws IOException {
        Process p=null;
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task(p));
        try {
            System.out.println("Started..");
            System.out.println(future.get(5, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException | InterruptedException | ExecutionException e) {
            future.cancel(true);
            //gives NullPointerException as expected after thread times out
            p.destroyForcibly();
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    Process p;

    public Task(Process p) {
        this.p = p;
    }
    @Override
    public String call() throws Exception {
        String s;
        String toDisplay = "";
        this.p = Runtime.getRuntime().exec("iperf3.exe -s -1");
        BufferedReader br = new BufferedReader(new InputStreamReader(this.p.getInputStream()));
        while ((s = br.readLine()) != null) {
            toDisplay += s + "\n";
        }
        p.destroyForcibly();

        return toDisplay;
    }
}

I am guessing I should somehow set main's Process but I have no idea how to aproach this problem

Grimalkin
  • 107
  • 12
  • What is the point in your ctor parameter? It's always null – Michael Aug 19 '22 at 11:36
  • "*gives NullPointerException as expected*" NPE should never be "expected". You can do `if (p != null) p.destroyForcibly();` Of course, in your case that condition will always be false. – Michael Aug 19 '22 at 11:37
  • Also you push the Task to a 2nd thread, only to block the original thread until it's done. You're really not getting the benefit of multiple threads, except that you get a free 5 second timeout mechanism – Michael Aug 19 '22 at 11:45
  • @Michael It is the best way I found to run Iperf server side, other ways I found did timeout the process but did't allow It to perform `BufferedReader.readLine()` simultaneously – Grimalkin Aug 19 '22 at 11:49
  • @Michael never mind I just modified my code to `Process p= Runtime.getRuntime().exec("iperf3.exe -s 127.0.0.1 -1");` from `Process p=null;` i don't know why I didn't do It initially – Grimalkin Aug 19 '22 at 11:53

0 Answers0