views:

110

answers:

1

I have the following scala code:

  package dummy
  import javax.servlet.http.{HttpServlet,
    HttpServletRequest => HSReq, HttpServletResponse => HSResp}
  import scala.actors.Actor

  class DummyServlet extends HttpServlet {
    RNG.start
    override def doGet(req: HSReq, resp: HSResp) = {
      def message = <HTML><HEAD><TITLE>RandomNumber </TITLE></HEAD><BODY>
           Random number = {getRandom}</BODY></HTML>
      resp.getWriter().print(message)
      def getRandom: String = {var d = new DummyActor;d.start;d.getRandom}
    }
    class DummyActor extends Actor {
      var result = "0"
      def act = { RNG ! GetRandom
        react { case (r:Int) => result = r.toString }
      }
      def getRandom:String = {
        Thread.sleep(300)
        result
      }
    }
  }

  // below code is not modifiable. I am using it as a library
  case object GetRandom
  object RNG extends Actor {
    def act{loop{react{case GetRandom=>sender!scala.util.Random.nextInt}}}
  }

In the above code, I have to use thread.sleep to ensure that there is enough time for result to get updated, otherwise 0 is returned. What is a more elegant way of doing this without using thread.sleep? I think I have to use futures but I cannot get my head around the concept. I need to ensure that each HTTP reaquest gets a unique random number (of course, the random number is just to explain the problem). Some hints or references would be appreciated.

+2  A: 

Either use:

!! <-- Returns a Future that you can wait for

or

!? <-- Use the one with a timeout, the totally synchronous is dangerous

Given your definition of RNG, heres some REPL code to verify:

scala> def foo = { println(RNG.!?(1000,GetRandom)) } 
foo: Unit

scala> foo
Some(-1025916420)

scala> foo
Some(-1689041124)

scala> foo
Some(-1633665186)

Docs are here: http://www.scala-lang.org/api/current/scala/actors/Actor.html

Viktor Klang
Its a good idea, except to use !! or !? in place of ! in the above code, I need to modify the RNG object (i.e., add a reply statement somewhere). At least, thats how I understood it. However, I am not allowed to modify that object.
Jus12
Given your definition of RNG it works just fine:scala> def foo = { println(RNG.!?(1000,GetRandom)) } foo: Unitscala> fooSome(-1025916420)scala> fooSome(-1689041124)scala> fooSome(-1633665186)
Viktor Klang
This is quite interesting. I had read that the receiving actor (i.e., `RNG`) must respond using `reply(message)` instead of using `sender ! message` in order for `!?` to work. However, it also works this way in my code. Is this something expected? Thanks for the tip, BTW.
Jus12