Running the command line program several times in Java - is this correct?

I have a program (in Java) that needs to use another program several times with different arguments during its execution. It is multi-threaded and should also perform other functions besides calling this program during its execution, so I need to use Java for this.

The problem is that all calls Runtime.exec()seem to be executed by Java in a synchronized way, so that the threads become narrow not only in the functions themselves, but also in the Java call. Thus, we have a very slow running program, but this is not a bottleneck on any system resource.

To fix this problem, I decided not to close the process and make all calls using this script:

#!/bin/bash

read choice
while [ "$choice" != "end" ]
do
   $choice
   read choice
done

exec :

private Process ntpProc;

Initializer(){
   try {
      ntpProc = Runtime.getRuntime().exec("./runscript.sh");
   } catch (Exception ex) {
      //Error Processing
   }
}

public String callFunction(String function) throws Exception e{
   OutputStream os = ntpProc.getOutputStream();
   String result = "";
   os.write((function + "\n").getBytes());
   os.flush();
   BufferedReader bis = new BufferedReader(new InputStreamReader(ntpProc.getInputStream()));
   int timeout = 5;
   while(!bis.ready() && timeout > 0){
      try{
         sleep(1000);
         timeout--;
      }
      catch (InterruptedException e) {}
   }
   if(bis.ready()){
      while(bis.ready()) result += bis.readLine() + "\n";
      String errorStream = "";
      BufferedReader bes = new BufferedReader(new InputStreamReader(ntpProc.getErrorStream()));
      while(bes.ready()) errorStream += bes.readLine() + "\n";
   }
   return result;
}

public void Destroyer() throws exception{
   BufferedOutputStream os = (BufferedOutputStream) ntpProc.getOutputStream();
   os.write(("end\n").getBytes());
   os.close();
   ntpProc.destroy();
}

, . , : ? - , , ?

+3
2

(aka stderr stdout), .

, , , .

, , , .

, Java , .

+3

Source: https://habr.com/ru/post/1774564/


All Articles