Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code in a separate thread?

Tags:

scala

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

like image 463
EECOLOR Avatar asked Apr 02 '13 19:04

EECOLOR


People also ask

How do you run a method in separate threads?

The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

How do you run a method in a new thread dotnet?

Threading; public class Work { public static void Main() { // Start a thread that calls a parameterized static method. Thread newThread = new Thread(Work. DoWork); newThread. Start(42); // Start a thread that calls a parameterized instance method.

Does Task run on different thread C#?

Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR. But that depends on the actual implementation of the task.


2 Answers

Yes, there is. You can use the scala.concurrent from the standard library. More specifically, you can use futures - highly composable asynchronous computations.

import java.util.concurrent.Executors
import concurrent.{ExecutionContext, Await, Future}
import concurrent.duration._

object Main extends App {

  // single threaded execution context
  implicit val context = ExecutionContext.fromExecutor(Executors.newSingleThreadExecutor())

  val f = Future {
    println("Running asynchronously on another thread")
  }

  f.onComplete { _ =>
    println("Running when the future completes")
  }

  Await.ready(f, 5.seconds) // block synchronously for this future to complete

}

Futures run in an execution context, which is an abstraction for thread pools. This context can be passed implicitly. In the above example, we used a global one, defined by the Scala library - but you can control this aspect of your program by allocating many execution contexts.

The snippet only does what you asked - running code concurrently. However, futures are much more than that - they allow you to compute values asynchronously, compose multiple futures to obtain results with dependencies amongst them, or in parallel.

Here's an intro: http://docs.scala-lang.org/overviews/core/futures.html

like image 94
Marius Danila Avatar answered Sep 27 '22 19:09

Marius Danila


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)
}
like image 20
EECOLOR Avatar answered Sep 27 '22 21:09

EECOLOR