Points to note when using the Java thread pool

Thread pool role

  • CPU resource isolation
  • reduce context switching
  • Reduce resource overhead of thread creation/closing
  • better concurrency control
  • Better lifecycle control

Design considerations

When designing, pay attention to:

  • mixed tasks
  • task dependent
  • starvation deadlock
  • slow operation

Precautions when using

thread pool parameters

  • core pool size
  • maximum pool size
    • core pool full
    • queue full
  • keep-alive time

Task Queue (BlockingQueue)

  • Unlimited queue
    • LinkedBlockingQueue
      • newSingleThreadExecutor
      • newFixedThreadPool
  • limited queue
    • ArrayBlockingQueue
    • LinkedBlockingQueue(int capacity)
    • saturation strategy
      • setRejectedExecutionHandler
      • ThreadPoolExecutor.AbortPolicy
        • Abort policy (default)
        • throwRejectedExecutionException
        • After the caller captures, implement the logic by itself
      • ThreadPoolExecutor.CallerRunsPolicy
        • Don't drop tasks
        • do not throw exceptions
        • Return the task to the caller thread for execution (synchronous call)
      • ThreadPoolExecutor.DiscardOldestPolicy
        • Abandon the oldest quest
        • Select the task that should be performed next
          • will try to submit again
        • If using a priority queue, discard the element with the highest priority
        • CooperateSynchronousQueue使用,可以实现任务提交并等待的效果
      • ThreadPoolExecutor.DiscardPolicy
        • abandonment strategy
        • give up this mission
      • can be Semaphoreused in combination
        • Limit task injection rate
    • FIFO
  • synchronous handoff
    • pass directly to other threads
    • SynchronousQueue
      • newCachedThreadPool

thread factory

  • Set exception handling
    • UncaughtExceptionHandler
  • set thread name
  • priority (not recommended)
  • Daemon thread (not recommended)
  • add extra counter
  • Add extra stats
  • Executors.privilegedThreadFactory()
    • Use the security policy of creating threads, ClassLoader

Not reconfigurable

  • Prevent the ExecutorService from being called externally to the setting method, thereby modifying the thread pool configuration
  • Executors.unconfigurableExecutorService()

thread pool extension point

  • ThreadPoolExecutor
    • beforeExecutor
    • afterExecutor
    • terminate

execution strategy

  • Perform tasks without caring about results
    • void execute(Runnable command)
  • Execute the task and need to process the result
    • Future submit(Callable task)
    • Future submit(Runnable task)
    • Future submit(Runnable task, T result)
  • Execute a batch of tasks, all of which need to be successfully completed
    • List<Future> invokeAll(Collection<? extends Callable<T>> tasks)
    • List<Future> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
  • Execute a batch of tasks, only one of them needs to complete successfully
    • T List<Future> invokeAny(Collection<? extends Callable<T>> tasks)
    • T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
  • Execute a batch of tasks and need to process the results one by one
    • CompletionService
      • ExecutorCompletionService

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324436709&siteId=291194637