-1

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;
}
Saif
  • 6,804
  • 8
  • 40
  • 61
Harshit Gupta
  • 719
  • 1
  • 9
  • 26

1 Answers1

1

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.

Saqib Rezwan
  • 1,382
  • 14
  • 20
  • But in this scenario condition will evaluate every time and this will cause execution of some extra statements and i dont want that in my code because i have a function in which the loop can process for 100000000 time. – Harshit Gupta Jun 25 '15 at 08:25
  • I just tried to point that the elapsed time and current time can be a way but this example was not a perfect one. Sorry that I could not be any help. – Saqib Rezwan Jun 26 '15 at 03:10
  • No need of sorry its just that i require some other kind of solution... But thanks for your efforts. – Harshit Gupta Jun 26 '15 at 04:33