简体   繁体   中英

Passing a ThreadFactory to the ScheduledThreadPoolExecutor

One of the constructors of ScheduledThreadPoolExecutor allows me to pass a ThreadFactory to it.

This is a bit weird since I am already dealing with a thread pool! Meaning it knows how to manage thread lifetime.

From my perspective, this looks like the strategy pattern, allowing me to override the logic of thread creation while maintaining the scheduling services it provides.

  1. I am getting it right?
  2. What are the built in ThreadFactories in Java?

Thank you!

ThreadFactory is typically used as a factory pattern to detail the way you create your threads.

A typical use case is naming your threads logically.

public WorkerThreadFactory implements ThreadFactory {
   private int counter = 0;

   public Thread newThread(Runnable r) {
     return new Thread(r, "Worker" + "-" + count++);
   }
}

This is a pretty exhaustive list of the use cases.

A built in implementation of ThreadFactory would be Executors.defaultThreadFactory()

These are the places where it is getting used.

It is always a good practice to use custom thread factory. The default factories are not much of use. You should use a custom factory for the following reasons:

  1. To have custom thread names
  2. To choose between thread types
  3. To choose Thread Priority
  4. To handle uncaught exceptions

Check this post: http://wilddiary.com/understanding-java-threadfactory-creating-custom-thread-factories/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM