Java - handling non-blocking calls
I am using a third party API in my application. It is a non-blocking method and returns immediately. I have a set of items on which I have to call this method.
Now my problem is that I need to find a way before the method finishes executing and perform the next operation. How can I handle this? I cannot change the third party API.
In short, it looks like
for(Object object: objects){
methodA(object); //this is a non-blocking call and returns immediately
}
// here I want to do my next task only after all the methodA calls completed execution
source to share
What you are asking for is not possible ... unless the third party API also has some method enabled that allows you to wait for one or more calls to complete methodA
.
It?
EDIT
As Katy Stone points out, another possibility is that the API can have a callback mechanism, whereby the thread (behind the API) that does the work started by the call methodA
"accesses" your code. (There must be some other method in the API that allows you to register the callback object.)
There are other possibilities ... (some of them are too dire) ... but they all entail an API designed to support synchronization with the completion of tasks started with methodA
.
source to share
As Stephen pointed out, this is possible if you have some way of knowing that the method has completed. If you have some kind of response or listener, you can use something like a counting semaphore:
final Semaphore block = new Semaphore();
//HERE SOMETHING APPROPRIATE TO YOUR API
myAPI.registerListener(new APIListener(){
public void methodADone(){
block.release();
}
});
int permits = 0;
for(Object object: objects){
methodA(object); //this is a non-blocking call and returns immediately
permits++;
}
block.acquire(permits);
Of course, you will need some extra checking to make sure you are issuing permissions on the correct collections of objects, depending on how your code is threaded and what kind of API mechanism exposes the call to complete, but this is one approach that could.
source to share
How will the call end methodA()
?
Does the method return any handle? Or does the object have some property that needs to be set by the call methodA()
? Collect them, do a sleep loop, and check for any remaining object descriptors or properties, each of which is removed from the rest if completed.
The wait code might look like this:
while(!remaining.isEmpty()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
continue;
}
Iterator<HandleOrObjectWithProperty> i = remaining.iterator();
while (i.hasNext()) {
HandleOrObjectWithProperty result = i.next();
if (result.handleHasFinishedOrPropertyIsSet()) {
i.remove();
}
}
}
source to share