Am working on a program in Java as shown below, the class is simply executing commands into the operating system level. Yet, sometimes we are facing a problem where the program get stuck, so the command never return any status, thus the thread does not terminate.
Now am trying to enhance the code, add an additional thing where I can kill specific threads. Am already capturing the ThreadId, so, is this doable?
public class ExecuteCmd implements Runnable {
String ProcessId;
String cmd;
BackendSQL bsql;
Logger myLogger;
Thread myThread;
public ExecuteCmd(String cmd, BackendSQL bsql, String ProcessId, Logger myLogger) {
this.ProcessId=ProcessId;
this.cmd=cmd;
this.bsql=bsql;
this.myLogger=myLogger;
}
public void run() {
int rc = 0;
try {
long ThreadId = Thread.currentThread().getId();
bsql.MarkRunning(ProcessId, ThreadId);
myLogger.debug("[ExecuteCmd] Command is: "+cmd);
String[] cmdFull = cmd.split(";");
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmdFull);
myLogger.info("[ExecuteCmd] [Threading] "+ ThreadId + ": Executing command");
myLogger.debug("[ExecuteCmd] Command is: "+cmd);
BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inStreamLine = null;
String inStreamLinebyLine=null;
while((inStreamLine = inStream.readLine()) != null) {
inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
}
myLogger.info("Command getInputStream: " + inStreamLinebyLine);
try {
rc = p.waitFor();
if (rc == 0) {
bsql.MarkCompleted(ProcessId);
}else{
bsql.MarkFailed(ProcessId);
}
} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}
}catch (IOException IOE) {
myLogger.error("IOException[ExecuteCmd]: " + IOE.getMessage());
}catch (Exception e) {
myLogger.error("Exception[ExecuteCmd]: " + e.getMessage());
}
}
}