I just want to insert a batch of tasks into it, and do not want to lost any one.
2 Answers
The queue should never drop jobs; it just has a limited number of threads that would be running at any specific time. The rest of the jobs will be queue'd up to take the next available thread as the other threads exit.
The order in which the jobs are executed is dependent on the Queue that you are using; priority queues, FIFO queue's etc...

- 4,315
- 1
- 22
- 28
-
2If a bounded queue is used (`ArrayBlockingQueue` or a bounded `LinkedBlockingQueue`), then submitting a task could result in `RejectedExecutionException` being thrown by the default rejection handler. This would happen if the maximum number of threads were already created, and all of them were full. And if `DiscardPolicy` or `DiscardOldestPolicy` were used as the rejection handler, obviously submissions could be lost. But in general, it looks like the API developers tried hard to make sure that the default response wouldn't be to silently lose jobs. – GargantuChet Jun 22 '11 at 03:05
@virsir,
You'd asked specifically about creating an instance ThreadPoolExecutor
. But I'm wondering whether it would be okay to have any class that implements the ExecutorService
interface. Since ThreadPoolExecutor
implements ExecutorService
, this isn't much of a leap.
The java.util.concurrent.Executors
class provides some useful functions for creating thread pools that handle some common situations.
I've recently used Executors.newFixedThreadPool()
in a project to create several different thread pools. It returns an object that implements ExecutorService. I had no trouble submitting tens of thousands of Runnable instances to a pool of 10 threads, and it worked quite smoothly.
Per the Java 5 docs, this method:
Creates a thread pool that reuses a fixed set of threads operating off a shared unbounded queue. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.
Since the method is said to create an "unbounded queue", there should be no artificial limits on the number of tasks one can submit.

- 5,691
- 1
- 30
- 41
-
This is great but what If I need the queue to be sortable ? Because I need to sort the jobs based on their priority. – Muhammad Gelbana Jul 11 '12 at 10:22
-
1@MuhammadGelbana, that's a somewhat different question with a more complex answer. Look at [this answer](http://stackoverflow.com/questions/3198660/java-executors-how-can-i-set-task-priority) or search the web for "Java executor priority queue". – GargantuChet Jul 11 '12 at 14:39