“关闭封闭范围/类”的含义是什么?意思? [英] What does "to close over the enclosing scope/class" mean?

查看:168
本文介绍了“关闭封闭范围/类”的含义是什么?意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Akka文档正在记录使用 Props 的危险变体:

The Akka documentation is documenting dangerous variants of using Props:

// NOT RECOMMENDED within another actor:
// encourages to close over enclosing class
val props7 = Props(new MyActor)

然后继续说明:


不建议在另一个参与者中使用此方法因为
鼓励关闭封闭范围,导致
不可序列化的道具,甚至可能产生种族状况(破坏
演员封装)。

This method is not recommended to be used within another actor because it encourages to close over the enclosing scope, resulting in non-serializable Props and possibly race conditions (breaking the actor encapsulation).

有人可以解释关闭封闭范围的含义吗?一直到处寻找,一无所获。谢谢。

Could someone please explain the meaning of "closing over the enclosing scope"? Been looking all over and found nothing. Thanks.

推荐答案

在此示例中看到 new Actor 作为所谓的按名称参数传递。认为它好像变成了()=>类型的函数一样。演员。每次在重新启动过程中由其主管重新创建actor时,都会调用此函数。

It's a bit tricky to see in this example, that the new Actor is passed in as a so called "by name" parameter. Think of it as if it is turned into a function of type () => Actor. This function will be called every time the actor will be (re)created by it's supervisor during a restart.

问题是此函数是关闭(非常易于Google;)),这意味着它可以捕获并记住其所需范围内的所有内容(有时,但很少被称为堆栈撕裂)。例如 val f =(a:Int)=> + x x 来自哪里?它来自周围的范围。分配给 f 的litetal函数称为开放术语。在运行时,函数文字变成函数值(这是一种对象的怪异方式),执行时会关闭开放项,同时捕获周围范围内的所有内容。

The problem is that this function is a "closure" (very easy to Google ;)), which means it captures and remembers everything in the surrounding scope that it needs (sometimes, but very rarely referred to as "stack ripping"). E.g val f = (a: Int) => a + x. Where does the x come from? It comes from the surrounding scope. The function litetal, assigned to f is called an "open term". At runtime the function literal becomes a function value (that's a fancy way of saying "object"), which when executed closes the open term, while capturing everything in the surrounding scope. That's where the name "closure" comes from.

关闭非常有用,但是关闭时必须小心。有时 x def ,或者上帝禁止 var ,导致 f 的结果无法预测,因为您无法控制调用 f 的时间/被执行。

Closures are very very useful, but you have to be careful what you close over. Sometimes x is a def or god forbid a var, which leads to unpredictable results for f, because you don't have control over the time when f will be called/executed. Try it out!

在Akka中有两种非常常见的反模式:

Two very common anti paterns in Akka are/were:


  1. 从内部类创建Actor
    时,关闭(外部)引用。

  2. 用将来响应
    a消息时关闭 def发件人

  1. Closing over (the outer) this reference when creating an Actor from an inner class.
  2. Closing over def sender when responding to a message with a future.

我特意给了你一些Google幻想的词,顺便说一句;)

I gave you a bunch of fancy terms to Google on purpose, btw ;)

欢呼和快乐的编码

这篇关于“关闭封闭范围/类”的含义是什么?意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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