Reputation: 3783
I am trying to get thread pool executor to work, and am just wondering if I have gone wrong somewhere with the following code:
public class testPool implements Runnable {
static Executor pooledExecutor = null;
private Threat thread = null;
private testPool(int minThreadPoolSize,
int initThreadPoolSize,
int maxThreadPoolSize,
int threadKeepAliveTime,
int queueCapacity) throws Exception {
pooledExecutor = new ThreadPoolExecutor(initThreadPoolSize,
maxThreadPoolSize,
(long) (1000 * threadKeepAliveTime),
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(queueCapacity));
this.thread = new Thread(this);
this.thread.setName("testThread");
try {
this.thread.setDaemon(true);
} catch (Exception e) {
// DO Something
}
}
public void run() {
while(true){
try {
// code to get a testobject
pooledExecutor.execute(testObject);
} catch (Exception e) {
//Do something
} finally {
//if shutdown parameter is true
break
}
}
}
}
Basically, I am not sure if this implementation will actually create the threads? or do I need to use a thread factory? Before I was using a pooledexecuter, which had a createThreads() method, but I cannot see anything like this.
Also is there any reason why someone would want to set a minimum thread pool size
Any help/advice would be greatly appreciated.
Upvotes: 2
Views: 1776
Reputation: 12398
Unless specified otherwise, ThreadPoolExecutor
uses a default ThreadFactory
that creates all threads in the same thread group.
If fewer than corePoolSize
threads are running, a new thread is created to handle every incoming request, even if other worker threads are idle. Keep-alive does not apply to core threads. Once the core threads were created, the executor will only create additional threads (up to maxPoolSize
) only when the queue is full.
If a new task is submitted when there are maxPoolSize threads and the queue is full, that task will be rejected. The behavior of the "rejection" is defined by the RejectedExecutionHandler
. By default, the rejection handler is AbortPolicy
(throw a runtime RejectedExecutionException upon rejection). You should analyze whether it is correct to use such policy, or perhaps set another one such as CallerRunsPolicy
(i.e. run the task in the thread that has invoked submit
, instead of enqueueing).
Upvotes: 1