I would like to know how a listener should let the parent thread know that it has been called. (Basically I'm trying to force an asynchronous call to be synchronous.) My example includes Android calls, but it's more a general synchronization question...
The method myMethod() requests that a SoundPool load a sound and notify a listener when the call is complete. I would like for myMethod() to wait until the listener has been called before returning. The code I came up with is:
void myMethod() {
SoundPool soundPool = ...;
final Lock object = new Object();
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener(){
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
synchronized(lock) {
lock.notify();
}
}});
synchronized(lock) {
int soundId = MediaUtil.loadSoundPool(soundPool, ...); // returns immediately
lock.wait();
}
}
(I left out try/catch for simplicity, although it's in the real code.) Normally, I'd also have a flag when communicating between two threads, but I can't use a local variable for this purpose, since it would have to be final to be accessible from the anonymous class, and an instance variable seems like an abstraction violation (and would have to be volatile).
Is the above code safe and/or is there a better way to solve the problem?