I have a spring @Controller that has a request mapping. When requests are sent to it it creates a deferred result and runs a method on a delegator class.
In the controller:
@ResponseBody
@RequestMapping(MenuModelCodes.MENU_NAME)
DeferredResult<HttpEntity<?>> getModelCodesWithClass(String target) {
final DeferredResult<HttpEntity<?>> deferredResult = getNewDeferredResult();
delegator.doStuff(target);
return deferredResult;
}
The doStuff method in the delegator is @Async annotated - so it's running in another thread. In this thread a new Phaser is created to keep track of child threads it will create. The delegator thread itself registers with the phaser, and triggers a call to a method in "AnotherClass" that is also @Async annotated. I.e. the delegator is now spawning children.
The delegator:
public class Delegator {
@Async
public Object doStuff(String requestURI) {
Phaser phaser = new Phaser();
phaser.register();
Object result = anotherClass.createThreadDoWork(phaser);
phaser.arriveAndDeregister();
//Wait until phaser is completed
while (!phaser.isTerminated()) {}
return result;
}
}
Each child spawned thread created by a call in the delegator to createThreadDoWork here registers itself with the phaser, does some work and then arrives and deregisters.
AnotherClass:
public class AnotherClass {
@Async
public void createThreadDoWork(Phaser phaser) throws Throwable {
phaser.register();
//some kind of logic / rest call etc.
phaser.arriveAndDeregister();
}
}
When all child threads complete, the delegator which is sitting at this piece of code:
while (!phaser.isTerminated()) {}
Will continue, set its deferred result and the delegator thread will end.
So here's the question(s):
I want a Phaser for every request - i.e. I create a new Phaser() everytime a request creates a new delegator thread.
If I receive 5 requests to my controller, they each spawn a delegator thread, each delegator creates a new Phaser and passes it to their children. However, as soon as one of the threads completes its processing and its specific instance of the Phaser is terminated, the other delegator threads continue and return without having done their tasks.
Can Phasers be used like this? Am I doing something wrong? I thought this would be a useful way to track the completion of child threads and wait for them to complete?
Thanks.