How to determine whether there are available threads in the thread pool in Java
I try to get the task queue from the database table as quickly as possible, while limiting the number of threads processing tasks
I want to know if there is a way to know whether the thread pool is full. I mean, there are currently 50 threads running. If so, I will wait for a thread to be available before starting a new thread instead of sleeping with the main thread
The code I want to do:
ExecutorService executor = Executors.newFixedThreadPool(N); ResultSet results; while( true ) { results = getWaitingTasksStmt.executeQuery(); while( results.next() && executor.notFull() ) { executor.submit( new thread( new runnableInheritedClass(results) ) ); } }
Solution
You should not submit a thread object to the executor, which will negate its full purpose You should submit the runnable object and let the executor worry about thread processing When all threads are busy, it will automatically queue runnables. When a task is completed, it will get the waiting task from the queue
So your code should look more like this:
ExecutorService executor = Executors.newFixedThreadPool(N); ResultSet results = getWaitingTasksStmt.executeQuery(); while( results.next() ) { executor.submit(new RunnableInheritedClass(results) ) ); } executor.shutdown(); executor.awaitTermination(10,TimeUnit.MINUTES);
This will allow all tasks to complete for 10 minutes, which can be adjusted according to your situation Waiting is discouraged, so think about a reasonable timeout for your task