向演员发送非演员的消息是不好的做法吗? [英] Is it bad practice to send an actor a message from something which is not an actor?

查看:78
本文介绍了向演员发送非演员的消息是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,其属性为 Actor 类型的属性 actor _ 。我这样做有问题吗?

Suppose I have some class which has a property actor_ of type Actor. Is there a problem with me doing

def someMethod() = {
  actor_ ! "HELLO"
}

或者应该始终由其他演员发送消息;例如,

Or should sending a message always be done from another actor; e.g.

def someMethod() = {
  Actor.actor { actor_ ! "HELLO" }
}


推荐答案

。当您从非角色代码向角色发送消息时,将自动创建一个ActorProxy并将其存储在本地线程中。这会造成潜在的内存泄漏,尽管很小,因为在线程被GC之前,ActorProxy不会被GC。 ActorProxy实际上使非演员线程在许多方面都可以像演员一样工作,包括接收消息。

It depends. When you send a message to an actor from non-actor code, an ActorProxy is automatically created and stored in a thread local. This creates a potential memory leak, albeit a very small one, because the ActorProxy won't be GC'd until the thread is GC'd. The ActorProxy essentially enables the non-actor thread to in many ways behave like an Actor, including receiving message.

更大的问题是,如果您的线程被管理,则类似于actor库管理线程的方式,因此表示逻辑上下文的内容可能一次在一个线程上,而在另一时间在另一个线程上。 Servlet容器就是一个很好的例子。您的逻辑上下文可以是servlet或会话,但是ActorProxy将绑定到线程,因此可以在逻辑上下文之间共享。如果您的演员没有回复ActorProxy,这没什么大不了的,但是如果他们是演员,则很可能会导致问题,因为(a)答复可能会被错误的上下文接收,或者(b)消息从未收到,因此前面提到的小漏洞随着ActorProxies邮箱的填满而成为一个大漏洞。

The bigger problem is if your thread being managed, similar to the way the actor library manages threads, so that what represents a logical context may at one time be on one thread, and at another time be on another thread. A good example of this would be a servlet container. Your logical context may be a servlet or a session, but the ActorProxy is going to be bound to the thread, and thus shared across logical contexts. If your actors aren't replying to the ActorProxy this isn't such a big deal, but if they are it will likely lead to problems because either (a) the replies will potentially be received by the wrong context, or (b) the messages are never received, and thus the previously mentioned small leak becomes a large one as the mailboxes of the ActorProxies fill up.

[Edit]
嗯。 。我似乎在阅读问题时遇到了问题!将其围绕在actor块中会创建一个新的actor对象,该对象在终止时将被GC正确处理。请记住,将消息发送放在参与者块中意味着消息发送将在另一个线程上进行新的响应,而不是在创建参与者的线程中进行。

Hmm...I seem to have a problem reading questions! Surrounding it in the actor block creates a new actor object that will be GC'd properly when it terminates. Keep in mind that putting the message send in an actor block means that the message send will be done in a new reaction on another thread, not in the thread creating the actor.

这篇关于向演员发送非演员的消息是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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