user11251855
user11251855

Reputation:

Are worker threads in ForkJoinPool are Daemon threads?

I am reading about Fork/Join Framework from book Java - The Complete Reference. It says that ForkJoinPool uses daemon threads :

ForkJoinPool uses daemon threads. A daemon thread is automatically terminated when all user threads have terminated. Thus, there is no need to explicitly shut down a ForkJoinPool. However, with the exception of the common pool, it is possible to do so by calling shutdown( ). The shutdown( ) method has no effect on the common pool.

  1. Does this means all ForkJoinWorkerThread are daemon threads?
  2. Since daemon threads are low priority threads, then we shouldn't use ForkJoinPool for important tasks?
  3. If worker threads are not daemon threads, then does shutdown() waits for worker threads to finish?

Upvotes: 2

Views: 1774

Answers (3)

Greg Brown
Greg Brown

Reputation: 3254

According to the Javadoc, "all worker threads are initialized with Thread.isDaemon() set true".

Upvotes: 1

kofemann
kofemann

Reputation: 4423

1.

jshell> ForkJoinPool.commonPool().execute(() ->  System.out.println(Thread.currentThread().getClass() + " isDaemon?  " + Thread.currentThread().isDaemon()))
class java.util.concurrent.ForkJoinWorkerThread isDaemon?  true

jshell>

A: yes, they are daemon threads.

2.

jshell> new Thread(() -> System.out.println("isDaemon? " + Thread.currentThread().isDaemon() + " priority:" +  Thread.currentThread().getPriority())).start()
isDaemon? false priority:5

jshell> ForkJoinPool.commonPool().execute(() -> System.out.println("isDaemon? " + Thread.currentThread().isDaemon() + " priority:" +  Thread.currentThread().getPriority()))
isDaemon? true priority:5

A: ForkJoinPool by default creates threads with the same priority as any other thread.

3.

from javadoc of ForkJoinPool#commonPool

Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts to shutdown() or shutdownNow(). However this pool and any ongoing processing are automatically terminated upon program System.exit(int). Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence, before exit.

A: ForkJoinPool ignores shutdown, but application can call awaitQuiescence​ to ensure that all task are complete.

Upvotes: 3

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

  1. yes
  2. no, the priority of daemon thread is the same as that of ordinary threads. Moreover, you can set their priority to the desired level. The referenced article just proposes to use daemon threads for less important tasks, as they are not guaranteed to finish their work when JVM exits.
  3. yes

Upvotes: 3

Related Questions