如何将 scala actor 添加到现有程序而不干扰正常终止行为?
该程序在执行 main() 后不会退出。
object Main
{
def main(args: Array[String]) {
... // existing code
f()
... // existing code
}
def f() {
import scala.actors.Actor._
val a = actor {
loop {
react {
case msg: String => System.out.println(msg)
}
}
}
a ! "hello world"
}
}
由于这种意想不到的副作用,使用 actor 可能会被视为侵入性的。
假设参与者必须继续运行直到程序终止,您将如何在所有终止情况下保留原始行为?
This program, after executing main(), does not exit.
object Main
{
def main(args: Array[String]) {
... // existing code
f()
... // existing code
}
def f() {
import scala.actors.Actor._
val a = actor {
loop {
react {
case msg: String => System.out.println(msg)
}
}
}
a ! "hello world"
}
}
Because of this unexpected side-effect, using actors can be viewed as intrusive.
Assuming the actors must continue to run until program termination, how would you do to preserve original behavior in all cases of termination?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
2.8 中有一个 DaemonActor 类允许这样做。在 2.7.x I 中,您可以侵入自定义调度程序,即使仍然存在实时演员,该调度程序也不会阻止关闭,或者如果您想要一种简单的方法,您可以在 main 末尾调用 System.exit() 。
如果您将 Actor 视为一种轻量级线程,那么大多数时候您需要一个实时 Actor 来防止程序终止。否则,如果您有一个程序在 Actor 中完成所有工作,则需要在主线程上放置一些东西以使其保持活动状态,直到所有 Actor 完成为止。
In 2.8 there's a DaemonActor class that allows this. In 2.7.x I you could hack in a custom scheduler that doesn't prevent shutdown even if there are still live actors, or if you want an easy way you could call System.exit() at the end of main.
If you think of an actor as kind of a light-weight thread, much of the time you want a live actor to prevent program termination. Otherwise if you have a program that does all of its work in actors, you'd need to have something on the main thread just to keep it alive until all the actors finish.
上例中的主线程完成后,程序仍然有一个非守护线程在运行 actor。使用 Thread.destroy() 或 System.exit() 粗暴地终止正在运行的线程通常是一个坏主意,因为结果可能对您的程序非常不利,包括但不限于数据损坏和死锁。这就是为什么 Thread.destroy() 和类似方法在 Java 中首先被弃用的原因。正确的方法是在线程中显式实现终止逻辑。对于 Scala actor,归结为向所有正在运行的 actor 发送一条 Stop 消息,并让它们在收到消息后退出。通过这种方法,您的示例将如下所示:
After the main thread in the above example completed, the program still had a non-daemon thread running the actor. It is usually a bad idea to brutally terminate running threads using Thread.destroy() or System.exit() for results may be very bad for your program including, but not limited to, data corruption and deadlocks. That is why Thread.destroy() and alike methods were deprecated in Java for the first place. The right way would be to explicitly implement termination logic in your threads. In case of Scala actors that boils down to sending a Stop message to all running actors and make them quit when they get it. With this approach your eample would look like this: