Scala actor to non-actor interaction (or synchronizing messages from an actor to a servlet)

浪子不回头ぞ 提交于 2019-12-11 02:14:09

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/3397991/scala-actor-to-non-actor-interaction-or-synchronizing-messages-from-an-actor-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!