Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.

I'm using Java.

to illustrate:

logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}

I figure the TestExecutor class should implement Callable and continue in that direction.

But all i want to be able to do is stop executor.execute() if it's taking too long.

Suggestions...?

EDIT

Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked. However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.

like image 759
carrier Avatar asked Oct 27 '08 15:10

carrier


People also ask

How do you wrap a method in Java?

wrap(int[] array, int offset, int length) The wrap() method wraps an int array into a buffer. The new buffer will be backed by the given int array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity will be array.

How do you stop a thread after some time?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.

How do you kill a thread?

Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.


2 Answers

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");
        }
    }
}
like image 74
Alex Avatar answered Nov 03 '22 07:11

Alex


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.

like image 28
Dan Dyer Avatar answered Nov 03 '22 07:11

Dan Dyer