Auto exception on time out in JAVA

64 views Asked by At

I need to create a method such that if I enter in that method and to if takes me more then 30 seconds to process that method then it should throw an exception and I will immediately get out from that method and I can handle that exception in the calling method so that my next process goes fine.

public static void method() {
    Timer timer=new Timer();
    timer.schedule(new TimerTask() {
        @SuppressWarnings("finally")
        @Override
        public void run() {
            try {
                System.out.println("inner "+Thread.currentThread());
                System.out.println("first ");
            }
            finally{ System.out.println("before return "); throw new RuntimeException("Sorry TimeOut");}
            } 
    },400);
    try{
        System.out.println(Thread.currentThread());
        Thread.sleep(1000);
        }catch(InterruptedException e){}
        System.out.println("OKKKKK");
    //return null;
}
1

There are 1 answers

3
Saqib Rezwan On

You can use System.currentTimeMillis() to elapse your initial/entry time and then check with current time. Then, compare how much time has been passed. if the desired limit of the time has not crossed then continue operation. If crossed then return or throw exception. Sample code has been given below:

public class Test{

public static void main( String[] argv) throws Exception{
    Timer timer=new Timer();
    timer.schedule(new TimerTask() {

          @Override
          public void run() {
            long currentTime = System.currentTimeMillis();
            int i = 0;
            while (i < 9999999){
                if ((System.currentTimeMillis()-currentTime)>(3*1000L)) {
                    System.out.println("Time is up");
                    return;
                }
                System.out.println("Current value: " + i);
                i++;
            }
          }
        }, 5*1000);
}
}

Now, here if the System.currentTimeMillis()-currentTime represents the time difference. If the time difference higher than 3 seconds then it will stop. Here, you can throw or whatever you want. Otherwise, it will continue to work.