Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executors.newSingleThreadExecutor() - how to see how many tasks are in queue

I am using Executors.newSingleThreadExecutor() in my code. I want to monitor number of tasks in queue to check that procesor is not overloaded with messages. How can I get a number of not completed submited tasks for curent moment? I expect something like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Runnable() {...});
executor.submit(new Runnable() {...});
executor.submit(new Runnable() {...});
// do something and get 3
...
// do something and get 2
...
// do something and get 1

Thanks

like image 412
General Jopa Avatar asked May 04 '11 12:05

General Jopa


1 Answers

Just in case you want to guarantee that even with new versions of the JVM the code suggested by FlorianOver will work, you could do it this way: (For the case that the method Executors.newSingleThreadExecutor() will no longer return an instance of type ThreadPoolExecutor)

ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

// ...

int queueSize = executor.getQueue().size();
like image 175
Danilo Tommasina Avatar answered Oct 02 '22 16:10

Danilo Tommasina