How to run code in a separate thread?
scala
Solution
Using the answer of @alexwriteshere as a basis I created this implementation:
import java.util.concurrent.Executors
import scala.concurrent.future
import scala.concurrent.JavaConversions.asExecutionContext
class ApplicationThread {
protected implicit val context =
asExecutionContext(Executors.newSingleThreadExecutor())
def run(code: => Unit) = future(code)
}
Update
Thanks to @Dth for pointing out that this is the modern version:
import java.util.concurrent.Executors
import scala.concurrent.{ExecutionContext, Future}
class ApplicationThread {
protected implicit val context =
ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
def run(code: => Unit) = Future(code)
}
Problem
I want to spawn a thread and run code in that thread. What are the options in Scala? Example usage would be something like this: ``` Thread.currentThread setName "MyThread" val myThreadExecutor = ??? val threadNamePromise = Promise[String] future { myThreadExecutor run { val threadName = "MySpecialThread" Thread.currentThread setName threadName threadNamePromise success threadName } } Await.result(threadNamePromise.future, Duration.Inf) future { myThreadExecutor run { println(Thread.currentThread.getName) // MySpecialThread } } future { myThreadExecutor run { println(Thread.currentThread.getName) // MySpecialThread } } println(Thread.currentThread.getName) // MyThread ``` Is there anything in the built-in Scala library that I can use? Edit I updated the snippet to better reflect intent