I am trying to schedule a job to run every 10 minutes using ScheduledThreadPoolExecutor. There are 10 threads in the thread pool. Code looks like:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10, r -> {
Thread t = new Thread(r);
t.setName("thread");
return t;
}, (runnable, pool) -> {
});
List<ScheduledFuture<?>> listOfFutures = new ArrayList<>();
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
try {
System.out.println("John is a good guy");
} catch (Exception e) {
// eat the exception
}
}, 0, 10, TimeUnit.MINUTES);
listOfFutures.add(future);
Now, if 100 tasks were scheduled and their future were added to a list. When we try to iterate the list and do future.cancel(), out of 100, 2-3 futures turn out to be null.
What is the possible reason here?
I had to add an initial delay of 2 seconds in order to ensure that the future is not null. But I also have an ExecutorService with the same problem (future is null in few cases). But there is no delay that can be added there.