Search code examples
javamultithreadingconcurrencyexecutor

What the reason to use Executors.defaultThreadFactory().newThread?


In our project I faced following method:

Thread t = Executors.defaultThreadFactory().newThread(new MyRunnable(importStartedTimestamp));
t.setName("my thread");
t.start();

I am wrong or first line is full analog of

Thread t = new Thread(new MyRunnable(importStartedTimestamp));

Please explain if first code snippet has advantages.

P.S.

I don't like to create redundant entities.


Solution

  • You are right. Executors.defaultThreadFactory().newThread().start() is verbose.

    The better use case for ThreadFactory is in Executors. ThreadFactory is accepted as argument, such as newCachedThreadPool(ThreadFactory threadFactory). In such case, you could change the ThreadFactory instance argument with changing client code.