Vitaliy
Vitaliy

Reputation: 8206

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!

Upvotes: 1

Views: 1997

Answers (2)

Drona
Drona

Reputation: 7234

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/

Upvotes: 0

Ajay George
Ajay George

Reputation: 11875

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.

Upvotes: 4

Related Questions