加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

窥视Scala Actor的邮箱的最佳方法

发布时间:2020-12-16 19:04:16 所属栏目:安全 来源:网络整理
导读:使用 Scala 2.8 RC1或更新版本,最好(最简单和/或最直接)的方法是“窥视”演员邮箱中的等待消息(来自同一个演员的act()方法),以便检查其中的内容队列,无需以任何方式响应/接收消息和/或干扰邮箱的当前内容. 这样做的目的是,参与者可以通过首先确定是否有任何
使用 Scala 2.8 RC1或更新版本,最好(最简单和/或最直接)的方法是“窥视”演员邮箱中的等待消息(来自同一个演员的act()方法),以便检查其中的内容队列,无需以任何方式响应/接收消息和/或干扰邮箱的当前内容.

这样做的目的是,参与者可以通过首先确定是否有任何剩余的邮箱消息是必须处理的消息来确定是否可以安全地处理退出请求,而不是通过立即停止该动作来删除.

解决方法

你不需要向前看.只需跟踪已请求退出的事实,并使用reactWithin(0)确定在请求退出后队列为空.

import scala.actors._

sealed case class Message
case object Exit extends Message
case class Unimportant(n:Int) extends Message
case class Important(n:Int) extends Message

class SafeExitingActor extends Actor {
  def act : Nothing = react {
      case Exit => {
           println("exit requested,clearing the queue")
           exitRequested
      }
      case message => {
           processMessage(message,false)
           act
      }
  }

  // reactWithin(0) gives a TIMEOUT as soon as the mailbox is empty
  def exitRequested : Nothing = reactWithin(0) {
     case Exit => {
         println("extra exit requested,ignoring")
         exitRequested // already know about the exit,keep processing
     }
     case TIMEOUT => {
         println("timeout,queue is empty,shutting down")
         exit // TIMEOUT so nothing more to process,we can shut down
     }
     case message => {
         processMessage(message,true)
         exitRequested
     }
  }

  // process is a separate method to avoid duplicating in act and exitRequested
  def processMessage(message : Any,importantOnly : Boolean) = {
     message match {
       case Unimportant(n) if !importantOnly => println("Unimportant " + n)
       case Unimportant(n) => () // do nothing
       case Important(n) => println("Important! " + n)
     }
     Thread sleep 100 // sleep a little to ensure mailbox backlog
  }
}

object TestProcessing {
  def main(args : Array[String]) {
    val actor = new SafeExitingActor()
    actor.start()
    for (i <- 1 to 10) {
        actor ! Unimportant(i)
        actor ! Important(i)
    }
    actor ! Exit
    for (i <- 11 to 20) {
        actor ! Unimportant(i)
        actor ! Important(i)
    }
    actor ! Exit
    actor ! Important(100)
  }
}

这应该输出

Unimportant 1
Important! 1
Unimportant 2
Important! 2
Unimportant 3
Important! 3
Unimportant 4
Important! 4
Unimportant 5
Important! 5
Unimportant 6
Important! 6
Unimportant 7
Important! 7
Unimportant 8
Important! 8
Unimportant 9
Important! 9
Unimportant 10
Important! 10
exit requested,clearing the queue
Important! 11
Important! 12
Important! 13
Important! 14
Important! 15
Important! 16
Important! 17
Important! 18
Important! 19
Important! 20
extra exit requested,ignoring
Important! 100
timeout,shutting down

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读