I have a task scheduled (@EnableSceduling) in a Spring Boot web service that repeats on a regular basis. When that task fires, it calls the registered object's Runnable/run method. In that run method, I need to do work and not exit that run method until the work is completed. The problem is that I have other threads doing other work that is needed by this run thread for its work. So in the run thread I have something like this:
@Component
public class DoWork implements Runnable {
@override
public void run() {
// Setup clients.
// Call services.
Mono<String> response1 = client1.post();
response1.subscribe(new MyResponseCallback(), new MyErrorCallback());
Mono<String> response2 = client2.post();
response2.subscribe(new MyResponseCallback(), new MyErrorCallback());
Mono<String> responseX = clientX.post();
responseX.subscribe(new MyResponseCallback(), new MyErrorCallback());
while(callbacksWorkCompletedFlag == false) {
Thread.sleep (1000);
}
// Do computation with callback responses.
// After computation is completed, exit run method.
}
}
public class MyResponseCallback implements Consumer<String> {
@override
public void accept (final Sting response) {
// Do work with response.
}
}
public class MyErrorCallback implements Consumer<Throwable> {
@override
public void accept (final Throwable error) {
// Log error.
}
}
Is there a better way to do this in Java/Spring boot?
Here is an example using
CompletableFuture. It uses the third parameter forMono.subscribeto let the future know when it's done.Here is a
CountDownLatchexample:Another
CompletableFutureexample:Are all the callbacks actually required?