开发者

Repeatedly Calling System.currentTimeMillis()/nanoTime()

开发者 https://www.devze.com 2023-01-23 02:09 出处:网络
I\'m trying create a Thread that keeps track of the time elapsed if a certain event has occurred/is happening. I want to be able to use the elapsed time outside of the thread, like:

I'm trying create a Thread that keeps track of the time elapsed if a certain event has occurred/is happening. I want to be able to use the elapsed time outside of the thread, like:

if(theChecker.elapsedTime > 5)
    doThis();

The code that I have basica开发者_如何学Clly looks like this:

public class Checker extends Thread {

    public int startTime, elapsedTime;

    @Override
    public void run() {
        while(true) {
            if(check()) {
                if(startTime == 0)
                    startTime = System.currentTimeMillis();
                elapsedTime = System.currentTimeMillis() - startTime;
            }
            else {
                startTime = 0;
                elapsedTime = 0;
            }
        }
     }

     private boolean check() {
         return isSomethingHappening();
     }            

}

As you can probably guess, this leads to horrendous issues with performance. I've gone as far as making the thread sleep for 250 ms after it calculates the elapsedTime, but performance is still problematic.

Is there a much more performance efficient way to go about this? I'm pretty sure it's something to do with the while loop continuously firing into oblivion, coupled with the fact that System.currentTimeMillis() isn't exactly a free call, memory wise.

Thanks for any replies.


Instead of having a thread poll for events in progress, I would suggest that you use an Observer pattern. With this, you could have your checker subscribe to the events that you are interested in. When the event fires, you could package some information about the event (including the timestamp) on a queue and then notify a reporting thread that the queue has been modified. The reporting thread can then pop from the queue and perform the work you have put together in your code above.


Don't store elapsedTime. Just calculate it when you need it.

public long getElapsedTime() {
    if (isSomethingHappening())
        return System.currentTimeMillis() - startTime;

    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消