3

Within my java application, I have a log backup function:

rt = Runtime.getRuntime();
pr = rt.exec(command);
int exitVal = pr.waitFor();

if(exitVal == 0) 
   return true

The problem is it takes a while to backup the logs and to get a response, until then my application freezes. If I remove the pr.waitFor() function call, I get a response, but the log backup fails to work.

Robert Valencia
  • 1,752
  • 4
  • 20
  • 36
Sameera.San
  • 67
  • 2
  • 15
  • Either you need to wait for it or you don't. Depending your exact context, you could use some kind of background thread to execute the process in and have some kind of observer which is notified when the process is done. `SwingWorker` from the Swing API does this (more or less) – MadProgrammer Apr 20 '17 at 05:05
  • Tried according to this and it works. http://stackoverflow.com/questions/3489543/how-to-call-a-method-with-a-separate-thread-in-java/3489549 – Sameera.San Apr 20 '17 at 10:04

2 Answers2

2

waitFor() method causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

So you can create another thread which do execution of command. pr = rt.exec(command); . You might have to perform this task asynchronously. Because until subprocess get terminated process will wait for.

Rahul Rabhadiya
  • 430
  • 5
  • 19
1

Yes you should do that work in a separate thread. Read about Runnable interface and Thread class

strash
  • 1,291
  • 2
  • 15
  • 29