How can I wrap a method so that I can kill its execution if it exceeds a specified timeout? How can I wrap a method so that I can kill its execution if it exceeds a specified timeout? multithreading multithreading

How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?


You should take a look at these classes : FutureTask, Callable, Executors

Here is an example :

public class TimeoutExample {    public static Object myMethod() {        // does your thing and taking a long time to execute        return someResult;    }    public static void main(final String[] args) {        Callable<Object> callable = new Callable<Object>() {            public Object call() throws Exception {                return myMethod();            }        };        ExecutorService executorService = Executors.newCachedThreadPool();        Future<Object> task = executorService.submit(callable);        try {            // ok, wait for 30 seconds max            Object result = task.get(30, TimeUnit.SECONDS);            System.out.println("Finished with result: " + result);        } catch (ExecutionException e) {            throw new RuntimeException(e);        } catch (TimeoutException e) {            System.out.println("timeout...");        } catch (InterruptedException e) {            System.out.println("interrupted");        }    }}


Java's interruption mechanism is intended for this kind of scenario. If the method that you wish to abort is executing a loop, just have it check the thread's interrupted status on every iteration. If it's interrupted, throw an InterruptedException.

Then, when you want to abort, you just have to invoke interrupt on the appropriate thread.

Alternatively, you can use the approach Sun suggest as an alternative to the deprecated stop method. This doesn't involve throwing any exceptions, the method would just return normally.


I'm assuming the use of multiple threads in the following statements.

I've done some reading in this area and most authors say that it's a bad idea to kill another thread.

If the function that you want to kill can be designed to periodically check a variable or synchronization primitive, and then terminate cleanly if that variable or synchronization primitive is set, that would be pretty clean. Then some sort of monitor thread can sleep for a number of milliseconds and then set the variable or synchronization primitive.