Scala actor与非actor的交互(或将消息从actor同步到servlet) [英] Scala actor to non-actor interaction (or synchronizing messages from an actor to a servlet)

查看:82
本文介绍了Scala actor与非actor的交互(或将消息从actor同步到servlet)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下scala代码:

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}}}
  }

在上面的代码中,我必须使用 thread.sleep 以确保有足够的时间用于更新 ,否则 0 返回。在不使用 thread.sleep 的情况下,这样做更优雅的方法是什么?我认为我必须使用期货,但是我无法理解这个概念。我需要确保每个HTTP重新请求都获得一个唯一的随机数(当然,随机数只是为了解释问题)。某些提示或参考将不胜感激。

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.

推荐答案

无论哪种使用:

!! <-返回一个可以等待的未来

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

!? <-使用带有超时的命令,完全同步是危险的

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

鉴于您对RNG的定义,这里有一些REPL代码来验证:

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)

文档在这里:> http://www.scala-lang.org/api/current/scala/actors/Actor .html

这篇关于Scala actor与非actor的交互(或将消息从actor同步到servlet)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆