views:

36

answers:

2

Hi!

I have implemented the following class which keeps track of the time needed to execute an algorithm

public class MyTimer extends Thread{

    long timeElapsed = 0;

    public MyTimer(String parameters){
        //initilise staff
    }

    pubic void run(){
      long startTime = System.currentTimeMillis();

      //DO SOME THINGS THAT TAKE TIME

      timeElapsed = System.currentTimeMillis() - startTime;
      System.out.println("time elapsed = " + timeElapsed");

    }
}

Some times the MyTimer do takes really a lot of time, so i would like to create another class to contol it. If the MyTimer hasn't finished in 30 sec then i would like the stop the thread and restart it with new parameters. if it finishes in less than 30 sec then i would like to be able to store the timeElapsed and restart the MyTimer again. I though that this would be simple but i have messed with thread pools timeCountLathces and monitor exceptions..... So, is there any way i can do it work? The alternative solution is to run my 500 tests one by one manually....

Thank you in advance

+2  A: 

Probably the problem that is making your life harder is that you must work out is how are you going interrupt your long running piece of code? If it's in a loop that itself is quite short (ie loops frequently), then you can do a check in the loop to decide whether to stop or keep going. That would be ideal. However, if the long running task is going off to a database or is a single java statement runs for ages, then you are going to have to try interrupting the thread (eg monitoredThread.interrupt()). Interrupting a running thread can cause errors to be logged etc but if the code is well behaved, the interrupt will cause it to stop doing what it's doing and return.

Hope that helps.

jowierun
thread.stop() is depricated but works fine with me! The code is just to save my time so there is no problem using the stop method. I tried interupt but it doesn't work as it is a recusive funtion i want to stop. I could use a check in the loop but i don't want to mess with the other program. Thanks for the help
Pitelk
A: 

You should consider just running your tests/build with Hudson. You can configure your Hudson build (your 500 tests) to automatically time out if it is not finished after a customizable period of time.

Sure you don't get the failure on a test-by-test basis, in that each test won't be given the arbitrary 30 seconds but you will be using Continuous Integration which is a step in the right direction.

Hudson takes around 5 minutes to download and setup: http://hudson-ci.org/

Syntax
thanks for the answer .. i will look into it
Pitelk