Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard Java pattern for wrapping a timeout around an errant process

I'm using a 3rd party function (say runThird()) that has a tendency to loop indefinitely and has no timeout facility built in. However, I can kill it (killThird()). Is there a proper way to do this (i.e. some concurrency construct)?

Here's my attempt at this:

java.lang.Thread thread = new Thread(new Runnable(){
    @Override
    public void run(){
        try {
            Thread.sleep(TIMEOUT);
        } catch (java.lang.InterruptedException e){
            return;
        }
        killThird();
    }
});                                
thread.start();

RunThirdResult rtr = runThird();

if (thread != null){
    thread.interrupt();
}

But I'm not sure I like the overhead of creating a thread, using sleep and the contrivance of interrupting the thread if runThird() returns.

like image 465
Bathsheba Avatar asked Jun 12 '13 10:06

Bathsheba


1 Answers

Let's assume runThird() retuns Integer ...

// ...  in your class ...
private ExecutorService executor = Executors.newCachedThreadPool();


//... then somewhere, where you want to call runThird()
Future<Integer> handle = executor.submit( new Callable<Integer>(){
    @Override Integer call(){
         return runThird(); // Assume you made it available here ...
    }
}

Integer result;
try{
   result = handle.get(TIMEOUT,UNIT); // TIMEOUT and UNIT declared somewhere above ...
}
catch(TimeoutException ex) {
   killThird();
   // HANDLE result not being set!
}

// ... use result.
like image 97
Fildor Avatar answered Sep 24 '22 06:09

Fildor