@Sotirios' answer is correct but I'd like to add some more specifics.
Is DefaultThreadFactory itself safe for concurrent use by multiple threads?
Yes. As Sotirios mentions, the only shared state is the thread-number which is handled with an AtomicInteger
.
Or must I take care to have only one DefaultThreadFactory per thread?
This is a bit contradictory. Each DefaultThreadFactory
is used by all threads created by a thread-pool. You can't have a thread-factory per thread but you can share thread-factories between pools if you'd like. The only reason why a new instance of the DefaultThreadFactory
is created for each pool is, I suspect, just to get a new thread-name counter for each pool.
I know it is generally best practice to start new threads only from one "main" thread...
This is not a common practice on any significantly complex multithreaded application. I fork threads or thread-pools from a large number of different classes. I'd rather have each class be responsible for its own background tasks then manage them in some central location.
why you are sure that DefaultThreadFactory is thread-safe or not.
See the code that Sotirios posted. If your question really is whether or not you have to write a thread-safe factory then it is enough to show how the java.util.concurrent
classes use it. Here a small code sample from ThreadPoolExecutor
which backs the Executors
thread pools.
private Thread addThread(Runnable firstTask) {
Worker w = new Worker(firstTask);
Thread t = threadFactory.newThread(w);
...
Notice that there is no locking around the use of factory. If you use the same factory in different thread-pools then multiple threads can certainly be executing it at the same time.