Akka关闭发件人 [英] akka closing over sender

查看:99
本文介绍了Akka关闭发件人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试了解以下发件人的使用是否安全。
我在某些帖子中看到,关闭发件人是不安全的,但是如果呼叫是按值,调用该方法时会评估sender(),对吗?
以下几种模式安全吗?

Trying to understand if the following use of sender are safe. I saw on some posts that closing over the sender is unsafe but if the call is by value, the sender() is evaluated when the method is called, correct? are the following patterns safe?

1。

上下文。 system.scheduler.scheduleOnce(1秒,自我, foo)(执行者= context.dispatcher,发件人= sender())

2。

def receive: Receive = {
    case "Process" => context.become(processing(sender())
}
def processing(replyTo: ActorRef): receive = {...}

3。

def receive: Receive = {
case "Process" => 
context.actorOf(Props(new FooActor(replyTo = sender())))
}


推荐答案

当人们对sender()函数说关闭时,他们的意思是将 this引用捕获到lambda中,以便sender()将会在以后的时间调用。这是不安全的,因为sender()在稍后的时间返回的值将与当前的值不同。如果捕获(或关闭)当前的值

When people say "closing" over the sender() function, they mean capturing the "this" reference into a lambda so that sender() will be called at a later time. This is not safe, because the value returned by sender() at a later time will not be the same as the value it currently has. If you capture (or "close over") the value currently returned by sender(), that is fine.

并不总是很清楚是将sender()捕获为函数还是将sender()捕获为值,因为它正如您所指出的,取决于将其传递给按值调用还是按名称调用函数。

It is not always clear whether you are capturing sender() as a function or sender() as a value, because it will vary depending on whether you pass it to a call-by-value or a call-by-name function, as you have pointed out.

Viktor指出你好s注释:

As Viktor points out in his comment:

1和2很好,因为您正在捕获sender()的当前值。

1 and 2 are fine, because you are capturing the current value of sender().

3不安全,因为 Props.apply 是传递名字的函数,因此您无意中将sender()作为函数而不是值进行了关闭。

3 is not safe, because "Props.apply" is a pass-by-name function, so you have inadvertently closed over sender() as a function rather than as a value.

我不知道有什么简单的方法可以区分这两种情况,其他而不是检查文档(或在IDE中单击(如果支持的话))。

I am not aware of any easy way to distinguish between these two cases, other than checking the docs (or clicking through in your IDE, if it supports it).

这篇关于Akka关闭发件人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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