Best wait syntax in Java

I have an animation running in the background and I want to register a callback when it's done. The animation is not standard java animation - it is c animation accessed through jni (so let's assume it is just an Object type).

The animation does not have an onFinish method to register, but it does have an isDone () method that returns a boolean value if the animation no longer works. To create the callback, I added the executable as such:

class Foo implements Runnable {
    @Override
    public void run() {
        if (animation == null || target == null) return;
        while (!animation.isDone())
        {
            //loop until animation is done...
        }
        //execute callback
    }
}

      

It looks like it would be a bad way to do it - just by running a loop until the animation ends. However, my question is, what are the alternative or preferred ways to wait for isDone () to return true in order to execute my callback?

+3


source to share


3 answers


Basically, if you have no control over the Animation class, and it only exposes the isDone () method, the only way is with what you did (but with Thread.sleep for a specific amount of time, like 10 or 50ms).

Otherwise, you can organize it using one of the following methods:



+2


source


If you cannot change the animation class use

while(!animation.isDone()){
    Thread.sleep(SOME_TIME);
}

      

But if you can change the behavior of the animation, then at the end of the animation (when isDone start return true) add something like this:



synchronized(this){
    this.notifyAll();
}

      

and instead in a loop you can use

synchronized(animation){
    if(!animation.isDone){
        animation.wait();
    }
}

      

+1


source


You can use a subscription template. You must register a callback with the animation so that when the animation ends, it will execute your callback.

Another option could be to use Futures if your animations are inside executables or callers.

0


source







All Articles