I have a method I am using to execute a command on the local host. I'd like to add a timeout parameter to the method so that if the command being called doesn't finish in a reasonable amount of time the method will return with an error code. Here's what it looks like so far, without the ability to timeout:
Can anyone suggest a good way for me to implement a timeout parameter?
Thanks Paul and Rob. The referenced JavaWorld article was helpful in that 1) I think it shows that you should always consume the output and error streams from the command whether or not you want them displayed, 2) it provides a good "StreamGobbler" class for consuming and displaying the output and error streams, and 3) it gives some good code examples on how to handle Windows commands (although I'm not planning to run my code on Windows, it's good to realize that this approach is not platform independent and should be coded accordingly). One thing I discovered as a result of tackling this problem is that the destroy() method is deprecated and was probably never even implemented, so I ended up not trying the approach described by Rob (but thanks for the suggestions nevertheless!).
In summary I used a worker thread which executes the command and to which I join my thread for the timeout period. If the worker thread completes within the timeout period then I return the result code, otherwise I assume that it has timed out.
James Adams wrote:One thing I discovered as a result of tackling this problem is that the destroy() method is deprecated and was probably never even implemented, so I ended up not trying the approach described by Rob (but thanks for the suggestions nevertheless!).
I wasn't talking about Thread.destroy() but Process.destroy(), which terminates your process. But that's called in that piece of code too, so I think that is a very good solution.
I would like to add one remark though: Worker.exit should be made volatile since it is used in two different threads.
Joined: Sep 12, 2003
Thanks, Rob, for the suggestion of making Worker.exit volatile, good catch.