我有以下斯卡拉代码:
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
确保有足够的时间进行result
更新,否则0
返回。在不使用的情况下,有什么更优雅的方式来做到这一点thread.sleep
?我想我必须使用期货,但我无法理解这个概念。我需要确保每个 HTTP 请求都获得一个唯一的随机数(当然,随机数只是为了说明问题)。一些提示或参考将不胜感激。