Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create non-blocking methods in Scala?

Tags:

scala

What is a good way of creating non-blocking methods in Scala? One way I can think of is to create a thread/actor and the method just send a message to the thread and returns. Is there a better way of creating a non-blocking method?

like image 793
Cory Avatar asked Sep 04 '09 12:09

Cory


3 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

Overloaded "asyncify" that takes a function with more than one parameter is left as an exercise.

One caveat, however, is exception handling. The function that is being "asyncified" has to handle all exceptions itself by catching them. Behavior for exceptions thrown out of the function is undefined.

like image 113
Walter Chang Avatar answered Nov 03 '22 06:11

Walter Chang


Learn about actors.

like image 20
Jesper Avatar answered Nov 03 '22 06:11

Jesper


It depends on your definition of "blocking." Strictly speaking, anything that requires acquisition of a lock is blocking. All operations that are dependent on an actor's internal state acquire a lock on the actor. This includes message sends. If lots of threads try to send a message to an actor all-at-once they have to get in line.

So if you really need non-blocking, there are various options in java.util.concurrent.

That being said, from a practical perspective actors give you something that close enough to non-blocking because none of the synchronized operations do a significant amount of work, so chances are actors meet your need.

like image 2
Erik Engbrecht Avatar answered Nov 03 '22 05:11

Erik Engbrecht