I am trying to steer away from using blocking thread model and use reactive model for achieving high throughput. The use case I have is this: There is a huge number of incoming messages. For every message I need to do some I/O without blocking that thread. Here I am processing each message in a separate thread. If the application is killed, I need to finish the ongoing tasks and shutdown gracefully. I am using Thread.sleep below to mimic the intensive I/O operation. The code sample is below:
public class TestReactor {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
Disposable task = Flux.range(1, 100).parallel().runOn(Schedulers.fromExecutor(executor)).doOnNext(message -> {
System.out.println(Thread.currentThread().getName()+": processing " + message);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": Done");
})
.sequential()
.doOnError(e->e.printStackTrace())
.doOnCancel(()->{
System.out.println("disposing.....");
executor.shutdown();
try {
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
})
.subscribe();
Thread.sleep(4000);
task.dispose();
System.out.println("Disposed. Waiting for sometime before exit.");
Thread.sleep(20000);
}
}
When I run this, the flux seems to ignore the executor.shutdown() and errors out with interrupted exceptions. Is it possible to achieve my use case using flux?