I have a webservice which calls this method
public void process(Incoming incoming) {
// code to persist data
...
Thread.sleep(20000);
// check persisted data and if status != CANCELLED then process
}
Requirement is that I have to wait 20 seconds (as business has high probability to send cancel request within 20 seconds in which case we should not process).
I understand that Thread.sleep() doesn't even bother the cpu until time's up.
Does scheduling an asynchronous task which runs after 20 seconds a better option? Here also, we have to have a Thread pool to execute these tasks anyway.
Yes, it is a better option, because with Thread.sleep(20000);
you are blocking one thread per each request. With scheduled thread pool, you are adding tasks to some kind of queue, and later they are executed using the constant number of threads - so there is no possibility of exhausting all available threads.