Mandroid
Mandroid

Reputation: 7484

Using ForkJoinPool in Scala

In code:

val executor = new ForkJoinPool()
executor.execute(new Runnable{
  def run = println("This task is run asynchronously")
})
Thread.sleep(10000)

This code prints: This task is run asynchronously

But if I remove Thread.sleep(10000), program doesn't print. I then learnt that its so because sleep prevents daemon threads in ForkJoinPool from being terminated before they call run method on Runnable object.

So, few questions:

  1. Does it mean threads started by ForkJoinPool are all daemon threads?Any why is it so?
  2. How does sleep help here?

Upvotes: 1

Views: 428

Answers (1)

jkinkead
jkinkead

Reputation: 4411

Answers:

  1. Yes, because you are using the default thread factory and that is how it is configured. You can provide a custom thread factory to it if you wish, and you may configure the threads to be non-daemon.

  2. Sleep helps because it prevents your program from exiting for long enough for the thread pool threads to find your task and execute it.

Upvotes: 2

Related Questions