How to get the number of tasks in a queue in executor service?

I think this should work:

    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) this.executorService;
    int activeCount = threadPoolExecutor.getActiveCount();
    long taskCount = threadPoolExecutor.getTaskCount();
    long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
    long tasksToDo = taskCount - completedTaskCount - activeCount;

For some reason though it does not always exclude all the cancelled tasks, only after some periodic clean ups. So I had to introduce a second counter:

    long tasksToDo2 = threadPoolExecutor.getQueue().stream().filter(t -> !((FutureTask) t).isDone()).count();