Please enable JavaScript.
Coggle requires JavaScript to display documents.
8.3 Configuring ThreadPoolExecutor - Coggle Diagram
8.3 Configuring ThreadPoolExecutor
Basic Use and Customization
Base for:
newCachedThreadPool
newFixedThreadPool
newScheduledThreadExecutor
Flexible and customizable
Can instantiate via constructor
Defaults available in Executors source
Thread Creation and Teardown
Core Pool Size:
Target number of threads
Maintained even if idle
Maximum Pool Size:
Upper limit of concurrent threads
Keep-Alive Time:
Idle threads beyond core size are terminated
Trade-off:
Resource efficiency vs. latency due to thread creation
Managing Queued Tasks
Work Queue Types:
Unbounded Queue:
E.g., LinkedBlockingQueue
Risk: unbounded growth
Bounded Queue:
E.g., ArrayBlockingQueue
Must tune with pool size
Risk: task rejection
SynchronousQueue (Direct Handoff):
Used by newCachedThreadPool
No queueing, tasks handed off directly
Requires pool growth or task rejection
Queue Selection Impacts:
Performance
Memory usage
Task ordering (e.g., PriorityBlockingQueue for custom order)
Saturation Policies
Triggered when:
Work queue full
Executor shut down
Built-in Policies (RejectedExecutionHandler):
AbortPolicy (default): throws exception
CallerRunsPolicy: caller thread runs task (slows submission)
DiscardPolicy: silently drops task
DiscardOldestPolicy: drops next task in queue
Note on Priority Queues:
DiscardOldest not ideal with PriorityBlockingQueue
Custom Blocking Behavior:
Use Semaphore + unbounded queue to control task injection rate
Thread Factories
Customize thread behavior:
Naming threads
Setting daemon status
Setting UncaughtExceptionHandler
Debug logging
ThreadFactory interface:
Method: newThread()
Privileged Threads:
Use privilegedThreadFactory to retain permissions and context
Post-Construction Configuration
Many options modifiable via setters:
Core/max pool size
Keep-alive time
Thread factory
Rejection handler
Casting for Access:
Factory methods (except newSingleThreadExecutor) return castable executors
Restricting Modification:
Use unconfigurableExecutorService to prevent reconfiguration
Prevents unsafe changes (e.g., increasing size of single-threaded executor)
Cautions and Trade-offs
Deadlock Risk:
Bounded pools + dependent tasks → starvation deadlock
Solution: use unbounded pool (e.g., newCachedThreadPool)
Throughput vs. Resource Use:
Large queues = lower memory/CPU use but potentially constrain throughput
Small queues = higher throughput but risk resource strain