SwiftMango
SwiftMango

Reputation: 15284

How to do an infinite loop without blocking CPU

How can I make this loop not using 100% CPU?

while(true){}

In the main thread, I do not want to quit, so I need to block the execution in the main thread, while allowing all other threads to continuously run. In Golang, there is an option:

select {}

which does not block CPU but also suspend main thread. How can I do this in Scala?

Upvotes: 2

Views: 253

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22605

The simplest answer to your question might be:

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

Await.result(Future.never, Duration.Inf) //semantic block

As the others have mentioned it might be better solutions for your problem( like deferred from cats-io), but it's hard to tell more without more details.

Upvotes: 5

Related Questions