How to create non-blocking methods in Scala?

What is a good way to create non-blocking methods in Scala? One way I can imagine is to create a thread / actor, and the method will just send a message to the stream and return. Is there a better way to create a non-blocking method?

+5
source share
4 answers

Use scala.actors.Future:

import actors._

def asyncify[A, B](f: A => B): A => Future[B] = (a => Futures.future(f(a)))

// normally blocks when called
def sleepFor(seconds: Int) = {
  Thread.sleep(seconds * 1000)
  seconds
}

val asyncSleepFor = asyncify(sleepFor)
val future = asyncSleepFor(5) // now it does NOT block
println("waiting...")         // prints "waiting..." rightaway
println("future returns %d".format(future())) // prints "future returns 5" after 5 seconds

The overloaded "asyncify", which accepts a function with several parameters, remains as an exercise.

One caveat is exception handling. A function that is "asynchronized" should handle all exceptions, catching them. The behavior for exceptions excluded from the function is undefined.

+13
source

.

+2

"". , , , . , , . . --, .

, , java.util.concurrent .

, , -, , , .

+2

I have a very detailed explanation on my futures blog. It actually shows you how you can implement futures yourself, and in this way you will get a very good understanding on this topic. I suggest you read it:

http://vigtig.it/blog/?p=73

Bring your coffee!

+1
source

All Articles