Scala Actor:JRE 1.5 和 1.6 上的不同行为

2022-09-03 07:46:00

我的模拟使用actor和Scala 2.8-Snapshot。在Java JRE 1.5中,它运行良好 - 所有40个齿轮(actor)同时工作。使用Java JRE 1.6,只有3个齿轮同时工作。我用和没有GUI测试了它:两者都给出了相同的结果。

我的GUI模拟可以在github上找到:http://github.com/pmeiclx/scala_gear_simulation

也许你还记得我和演员的第一个问题。在解决了这些问题之后,我为模拟做了一个GUI,我得到了这个新的“奇怪”的行为。

下面是没有 GUI 的代码:

package ch.clx.actorversions

import actors.Actor
import actors.Actor._
import collection.mutable.ListBuffer

case class ReceivedSpeed(gear: Gear)
case object StartSync

case class SyncGear(controller: GearController, syncSpeed: Int)

object ActorVersion {

  def main(args:Array[String]) = {
    println("[App] start with creating gears")
    val gearList = new ListBuffer[Gear]()
    for (i <- 0 until 100) {
      gearList += new Gear(i)
    }

    val gearController = new GearController(gearList)

    gearController.start()
    gearController ! StartSync
  }
}

/**
 * CONTROLLER
 */
class GearController(nGears: ListBuffer[Gear]) extends Actor {
  private var syncGears = new ListBuffer[Gear]
  private var syncSpeed = 0
  def act = {
    while(true) {
      receive {
        case StartSync => {
          println("[Controller] Send commands for syncing to gears!")
          var speeds = new ListBuffer[Int]
          nGears.foreach(e => speeds += e.speed)

          //Calc avg
          //var avgSpeed = speeds.foldLeft(0)(_ + _) / speeds.length
          //var avgSpeed = speeds.foldLeft(0) { (x, y) => x + y } / speeds.length
          syncSpeed = (0/:speeds)(_ + _) / speeds.length //Average over all gear speeds

          //TODO syncSpeed auf Median ausrichten

          println("[Controller] calculated syncSpeed: "+syncSpeed)
          nGears.foreach{e =>
                         e.start()
                         e ! SyncGear(this, syncSpeed)
          }
          println("[Controller] started all gears")
        }
        case ReceivedSpeed(gear: Gear) => {
          println("[Controller] Syncspeed received by a gear ("+gear.gearId+")")
          //println("[Controller] mailboxsize: "+self.mailboxSize)
          syncGears += gear
          if(syncGears.length == nGears.length) {
            println("[Controller] all gears are back in town!")
            System.exit(0)
          }
        }
        case _ => println("[Controller] No match :(")
      }
    }
  }
}

/**
 * GEAR
 */
class Gear(id: Int) extends Actor {

  private var mySpeed = scala.util.Random.nextInt(1000)
  private var myController: GearController = null

  def speed = mySpeed
  def gearId = id

  /* Constructor */
  println("[Gear ("+id+")] created with speed: "+mySpeed)

  def act = {
    loop {
      react {
        case SyncGear(controller: GearController, syncSpeed: Int) => {
          //println("[Gear ("+id+")] activated, try to follow controller command (form mySpeed ("+mySpeed+") to syncspeed ("+syncSpeed+")")
          myController = controller
          adjustSpeedTo(syncSpeed)
        }
      }
    }
  }

  def adjustSpeedTo(targetSpeed: Int) = {
    if(targetSpeed > mySpeed) {
      mySpeed += 1
      self ! SyncGear(myController, targetSpeed)
    }else if(targetSpeed < mySpeed) {
      mySpeed -= 1
      self ! SyncGear(myController, targetSpeed)
    } else if(targetSpeed == mySpeed) {
      callController
    }
  }

  def callController = {
    println("[Gear ("+id+")] has syncSpeed")
    myController ! ReceivedSpeed(this)
  }
}

答案 1

简短的回答:将控制器更改为使用循环/反应而不是 while/接收

actors库检测它运行的Java版本,如果它是1.6(而不是IBM的VM),它使用捆绑版本的JSR-166y fork join线程池,因此根据Java版本,底层实现存在很大差异。

分叉/联接线程池使用一种两级队列来执行任务。每个工作线程都有一个队列,并且池中有一个共享队列。源自分叉/联接线程的任务直接进入分叉/联接线程的队列,而不是通过主队列。线程之间的任务窃取用于使线程保持繁忙并帮助避免饥饿。

在你的例子中,启动齿轮的所有任务最终都会在运行控制器的线程的队列中结束。因为你在那个actor中使用了while/receive,所以它永远不会离开线程,所以它永远不会直接在其队列上执行任务。其他线程经常忙于3个齿轮,因此它们从不尝试从运行控制器的线程中窃取工作。结果是其他齿轮演员永远不会被执行。

在控制器中切换到循环/反应应该可以解决这个问题,因为在每个循环中,actor都会离开线程并调度一个新任务,该任务最终将在队列的后面结束,因此将执行其上的其他任务。


答案 2

使用Java JRE 1.6,只有3个齿轮同时工作。

您的意思是:

  • 只有三个档位朝着目标速度前进。当三个档位达到目标速度时,不再有任何档位取得任何进展。
  • 任何时候只有三个齿轮取得进展。当三个齿轮中的一个达到目标速度时,另一个齿轮开始前进,直到所有齿轮都达到目标速度。

我猜第二个?

观察到的行为的差异可能归结为JVM实现的差异 - JRE 1.5和JRE 1.6之间存在更改。其中一些更改可以关闭,例如,通过设置如下所示的标志:

-XX:ThreadPriorityPolicy=1

...但第二种行为是执行代码的完全有效方法。它只是不是你所期望的,因为它违反了你拥有的“公平”概念,但工作调度程序却没有。您可以添加某种时钟演员,以确保最受青睐的装备比最不喜欢的演员多获得不超过(例如)10个“滴答”的”

JRE之间的区别很难在不了解的情况下进行研究:

  • 您使用的是哪个 JRE 更新版本。
  • 您运行的操作系统。
  • 您有多少个 CPU 和内核。
  • 代码是否已针对 JRE 1.6 重新编译。

祝你好运!


推荐