tags:

views:

231

answers:

3

So I want to write some network code that appears to be blocking, without actually blocking a thread. I'm going to send some data out on the wire, and have a 'queue' of responses that will come back over the network. I wrote up a very simple proof of concept, inspired by the producer/consumer example on the actor tutorial found here: http://www.scala-lang.org/node/242

The thing is, using receive appears to take up a thread, and so I'm wondering if theres anyway to not take up a thread and still get the 'blocking feel'. Heres my code sample:

import scala.actors.Actor._;
import scala.actors.Actor;

case class Request(val s:String);

case class Message(val s:String);

class Connection  {
  private val act:Actor = actor {
     loop {
      react {
        case m:Message =>  receive { case r:Request => reply { m } }
      } 
    }
}

  def getNextResponse(): Message = {
    return (act !? new Request("get")).asInstanceOf[Message];
  }

  //this would call the network layer and send something over the wire
  def doSomething() {
    generateResponse();
  }

  //this is simulating the network layer getting some data back 
  //and sending it to the appropriate Connection object
  private def generateResponse() {
   act ! new Message("someData");
   act ! new Message("moreData");    
   act ! new Message("even more data");
  }

}


object runner extends Application {
 val conn = new Connection(); 
    conn.doSomething();
    println( conn.getNextResponse());
    println(conn.getNextResponse());
    println(conn.getNextResponse());
}

Is there a way to do this without using the receive, and thereby making it threadless?

+2  A: 

I expect that you can use react rather than receive and not have actors take up threads like receive does. There is thread on this issue at receive vs react.

faran
+3  A: 

You could directly rely on react which should block and release the thread:

class Connection  {
  private val act:Actor = actor {
    loop {
      react {
        case r:Request => reply { r }
      } 
    }
  }
[...]
paradigmatic
+1  A: 

Ok, what I exactly wanted to do was described in here: http://lampwww.epfl.ch/~odersky/papers/jmlc06.pdf

runT1ME