Search code examples
javaandroidmultithreadingasynchronouswait

Waiting for multiple callbacks in Android


In Java threads, you could have some number of threads in a list, start them off, and have a main thread join one, then another, going through and waiting for all processes to complete before moving on.

In other models, I'm not sure how you would do that. Take the RootTools 3.0 Command class for example. You create a Command which has three methods, commandOutput, commandFinished, commandTerminated, and while you can use a callback to do something at the end of a process, I don't know how you would wait for multiple processes (For example, going through listing of several directories and summing the file-sizes).

I believe the Android Asynctask would have a similar problem - you can easily make a callback, but there is no way to wait for several tasks. Unless I'm missing something?


Solution

  • You can call wait() on the command that you are executing.

    Although before doing this you should turn off the handler for the command that you call wait on. You can do that for every command by setting RootTools.handlerEnabled to false or by using the constructor in each individual command and passing in false to disable the handler for that command.

    This is important because if the handler is used then it will try to call the callback methods on the thread that you called wait() and that will result in a deadlock.

    When you turn the handler off for the command and call wait() the command will call notifyAll() when it completed so your thread will resume.

    The negative side of this is that the callback methods will no longer be done in the thread that you are working on so you will not be able to do any UI work from those callback methods unless you implement a handler or some other acceptable solution to deal with this.