Exit the app before the future is completed.

From what I understand, the future will be handled by a new thread from the thread pool. Meanwhile, the main thread can continue to perform its calculations, which do not depend on the outcome of the Future.

This, from https://www.playframework.com/documentation/2.4.x/ThreadPools , supports my understanding.

Please note that you may be tempted to lock your blocking code in Futures. This does not make it non-blocking, it just means that the blocking will happen on a different thread. You still need to make sure the thread pool you are using has enough threads to handle the lock.

Also, the JVM lacks the concept of parent children among threads. In other words, all streams are treated the same. This means that a thread addressed to the Future will continue to run even when the main thread ends.

However, in the following example, why is the Future thread killed when the main thread ends. If I don't comment on sleep (10000) at the end of the example, I can see the result in the future.

val f3 = Future {
  sleep(5000)
  2
}

f3.onComplete {
  case Success(value) => println(s"f3 result = $value")
  case Failure(e) => e.printStackTrace
}

// do other work
println("A ...")
sleep(100)
println("B ...")
sleep(100)
println("C ...")
sleep(100)
println("D ...")
sleep(100)
println("E ...")
sleep(100)
println("F ...")
sleep(100)

// keep the JVM running
//  sleep(10000)

def sleep(duration: Long) {
  Thread.sleep(duration)
}

      

+3


source to share





All Articles