Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time out method in java

Tags:

java

In a java class I have a method that sometimes takes a long time for execution. Maybe it hangs in that method flow. What I want is if the method doesn't complete in specific time, the program should exit from that method and continue with the rest of flow.

Please let me know is there any way to handle this situation.

like image 431
Ran Avatar asked Jan 24 '12 05:01

Ran


People also ask

How do you do a timeout in java?

How do you do a timeout in Java? In Java, to execute any code after some delay, we use wait or sleep() functions similarly, in javascript we have setTimeout () method, and the time specified within this function will be in milliseconds.

How do you stop a program from few seconds in java?

The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.

How do I stop a java method from running?

Exit a Java Method using Return return keyword completes execution of the method when used and returns the value from the function. The return keyword can be used to exit any method when it doesn't return any value.


2 Answers

You must use threads in order to achieve this. Threads are not harmful :) Example below run a piece of code for 10 seconds and then ends it.

public class Test {
    public static void main(String args[])
        throws InterruptedException {

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("0");
                method();
            }
        });
        thread.start();
        long endTimeMillis = System.currentTimeMillis() + 10000;
        while (thread.isAlive()) {
            if (System.currentTimeMillis() > endTimeMillis) {
                System.out.println("1");
                break;
            }
            try {
                System.out.println("2");
                Thread.sleep(500);
            }
            catch (InterruptedException t) {}
        }


    }

    static void method() {
        long endTimeMillis = System.currentTimeMillis() + 10000;
        while (true) {
            // method logic
            System.out.println("3");
            if (System.currentTimeMillis() > endTimeMillis) {
                // do some clean-up
                System.out.println("4");
                return;
            }
        }
    }
}
like image 112
Muhammad Imran Tariq Avatar answered Sep 20 '22 10:09

Muhammad Imran Tariq


Execute the method in a different thread, you can end a thread at anytime.

like image 30
COD3BOY Avatar answered Sep 17 '22 10:09

COD3BOY