From 59b26fc633a9ba78f750315ec4449ba4ae62f846 Mon Sep 17 00:00:00 2001 From: Arunav Sanyal Date: Sat, 5 Nov 2022 17:59:13 -0700 Subject: [PATCH] Delete actors.md --- _data/overviews-ja.yml | 7 - _data/overviews-ru.yml | 7 - _data/overviews-uk.yml | 7 - _data/overviews-zh-cn.yml | 7 - _data/overviews.yml | 7 - _es/overviews/core/actors.md | 494 ------------------------------- _overviews/core/actors.md | 506 -------------------------------- _zh-cn/overviews/core/actors.md | 306 ------------------- 8 files changed, 1341 deletions(-) delete mode 100644 _es/overviews/core/actors.md delete mode 100644 _overviews/core/actors.md delete mode 100644 _zh-cn/overviews/core/actors.md diff --git a/_data/overviews-ja.yml b/_data/overviews-ja.yml index 225eda4b6e..a76dd2bf72 100644 --- a/_data/overviews-ja.yml +++ b/_data/overviews-ja.yml @@ -258,13 +258,6 @@ - category: レガシー description: "最近の Scala バージョン(2.12以上)には関係なくなった機能をカバーするガイド。" overviews: - - title: Scala アクター API - by: Philipp Haller and Stephen Tu - icon: users - url: "core/actors.html" - description: "このガイドは Scala 2.8/2.9 の scala.actors パッケージの API を説明する。組織は論理的に同類の型のグループに従う。トレイト階層は個々のセクションを構造化することを考慮している。既存の Scaladoc ベースの API ドキュメントを補間するため、これらトレイトが定義する様々なメソッドの実行時の挙動にフォーカスする。" - label-color: "#899295" - label-text: deprecated - title: Scala 2.8 から 2.12 までのコレクション by: Martin Odersky icon: sitemap diff --git a/_data/overviews-ru.yml b/_data/overviews-ru.yml index d9176392d7..f4a652a032 100644 --- a/_data/overviews-ru.yml +++ b/_data/overviews-ru.yml @@ -258,13 +258,6 @@ - category: Наследие description: "Руководство по функционалу, которые больше не соответствуют последним версиям Scala (2.12+)." overviews: - - title: API Scala Акторов - by: Philipp Haller и Stephen Tu - icon: users - url: "core/actors.html" - description: "В данном руководстве описывается API пакета scala.actors версии 2.8/2.9. Сгруппированы по типам, которые логически принадлежат друг другу. Иерархия трейтов учитывается при структурировании отдельных разделов. Основное внимание уделяется поведению во время исполнения различных методов, которое дополняет существующую документацию по API на основе Scaladoc." - label-color: "#899295" - label-text: устарело - title: Scala коллекции с 2.8 по 2.12 by: Martin Odersky icon: sitemap diff --git a/_data/overviews-uk.yml b/_data/overviews-uk.yml index dacdb2f29c..02be500922 100644 --- a/_data/overviews-uk.yml +++ b/_data/overviews-uk.yml @@ -299,13 +299,6 @@ - category: Спадщина (legacy) description: "Посібники, що охоплюють функції, які більше не стосуються останніх версій Scala (2.12+)." overviews: - - title: API фреймворку Scala Actors - by: Philipp Haller та Stephen Tu - icon: users - url: "core/actors.html" - description: "У цьому посібнику описано API пакету scala.actors Scala 2.8/2.9. Організація слідує за групами типів, які логічно належать один до одного. Для структурування окремих розділів враховується ієрархія ознак. Основна увага приділяється поведінці під час виконання різних методів, що визначаються цими ознаками, тим самим доповнюючи документацію API, що існує на основі Scaladoc." - label-color: "#899295" - label-text: застаріле - title: Колекції Scala з 2.8 до 2.12 by: Martin Odersky icon: sitemap diff --git a/_data/overviews-zh-cn.yml b/_data/overviews-zh-cn.yml index a380c09508..1c48218eef 100644 --- a/_data/overviews-zh-cn.yml +++ b/_data/overviews-zh-cn.yml @@ -263,13 +263,6 @@ - category: 遗留问题 description: "涵盖一些与最近的 Scala 版本(2.12+)不再相关的特性的参考" overviews: - - title: Scala Actors API - by: Philipp Haller and Stephen Tu - icon: users - url: "core/actors.html" - description: "本篇描述了 Scala 2.8/2.9 下 scala.actors 包的 API。其组织方式遵循逻辑上属于一块的组类型,特质层是考虑到组成其各自的部分,主要关注点在这些特质所定义的各种方法的运行时表现,由此也增补了已有的基于 Scaladoc 的API文档。" - label-color: "#899295" - label-text: 弃用 - title: Scala 2.8 到 2.12 的容器 by: Martin Odersky icon: sitemap diff --git a/_data/overviews.yml b/_data/overviews.yml index 74d4662cdb..1e40bdfea3 100644 --- a/_data/overviews.yml +++ b/_data/overviews.yml @@ -309,13 +309,6 @@ - category: Legacy description: "Guides covering features no longer relevant to recent Scala versions (2.12+)." overviews: - - title: The Scala Actors API - by: Philipp Haller and Stephen Tu - icon: users - url: "core/actors.html" - description: "This guide describes the API of the scala.actors package of Scala 2.8/2.9. The organization follows groups of types that logically belong together. The trait hierarchy is taken into account to structure the individual sections. The focus is on the run-time behavior of the various methods that these traits define, thereby complementing the existing Scaladoc-based API documentation." - label-color: "#899295" - label-text: deprecated - title: Scala 2.8 to 2.12’s Collections by: Martin Odersky icon: sitemap diff --git a/_es/overviews/core/actors.md b/_es/overviews/core/actors.md deleted file mode 100644 index 19851b6c26..0000000000 --- a/_es/overviews/core/actors.md +++ /dev/null @@ -1,494 +0,0 @@ ---- -layout: singlepage-overview -title: API de actores en Scala - -partof: actors - -language: es ---- - -**Philipp Haller and Stephen Tu** - -**Traducción e interpretación: Miguel Ángel Pastor Olivar** - -## Introducción - -La presente guía describe el API del paquete `scala.actors` de Scala 2.8/2.9. El documento se estructura en diferentes grupos lógicos. La jerarquía de "traits" es tenida en cuenta para llevar a cabo la estructuración de las secciones individuales. La atención se centra en el comportamiento exhibido en tiempo de ejecución por varios de los métodos presentes en los traits anteriores, complementando la documentación existente en el Scaladoc API. - -## Traits de actores: Reactor, ReplyReactor, y Actor - -### The Reactor trait - -`Reactor` es el padre de todos los traits relacionados con los actores. Heredando de este trait podremos definir actores con una funcionalidad básica de envío y recepción de mensajes. - -El comportamiento de un `Reactor` se define mediante la implementación de su método `act`. Este método es ejecutado una vez el `Reactor` haya sido iniciado mediante la invocación del método `start`, retornando el `Reactor`. El método `start`es *idempotente*, lo cual significa que la invocación del mismo sobre un actor que ya ha sido iniciado no surte ningún efecto. - -El trait `Reactor` tiene un parámetro de tipo `Msg` el cual determina el tipo de mensajes que un actor es capaz de recibir. - -La invocación del método `!` de un `Reactor` envía un mensaje al receptor. La operación de envío de un mensaje mediante el operador `!` es asíncrona por lo que el actor que envía el mensaje no se bloquea esperando a que el mensaje sea recibido sino que su ejecución continua de manera inmediata. Por ejemplo, `a ! msg` envia `msg` a `a`. Todos los actores disponen de un *buzón* encargado de regular los mensajes entrantes hasta que son procesados. - -El trait `Reactor` trait también define el método `forward`. Este método es heredado de `OutputChannel` y tiene el mismo efecto que el método `!`. Aquellos traits que hereden de `Reactor`, en particular el trait `ReplyActor`, sobreescriben este método para habilitar lo que comunmente se conocen como *"implicit reply destinations"* (ver a continuación) - -Un `Reactor` recibe mensajes utilizando el método `react`. Este método espera un argumento de tipo `PartialFunction[Msg, Unit]` el cual define cómo los mensajes de tipo `Msg` son tratados una vez llegan al buzón de un actor. En el siguiente ejemplo, el actor espera recibir la cadena "Hello", para posteriomente imprimir un saludo: - - react { - case "Hello" => println("Hi there") - } - -La invocación del método `react` nunca retorna. Por tanto, cualquier código que deba ejecutarse tras la recepción de un mensaje deberá ser incluido dentro de la función parcial pasada al método `react`. Por ejemplo, dos mensajes pueden ser recibidos secuencialmente mediante la anidación de dos llamadas a `react`: - - react { - case Get(from) => - react { - case Put(x) => from ! x - } - } - -El trait `Reactor` también ofrece una serie de estructuras de control que facilitan la programación utilizando el mecanismo de `react`. - -#### Terminación y estados de ejecución - -La ejecución de un `Reactor` finaliza cuando el cuerpo del método `act` ha sido completado. Un `Reactor` también pueden terminarse a si mismo de manera explícita mediante el uso del método `exit`. El tipo de retorno de `exit` es `Nothing`, dado que `exit` siempre dispara una excepción. Esta excepción únicamente se utiliza de manera interna y nunca debería ser capturada. - -Un `Reactor` finalizado pueden ser reiniciado mediante la invocación de su método `restart`. La invocación del método anterior sobre un `Reactor` que no ha terminado su ejecución lanza una excepción de tipo `IllegalStateException`. El reinicio de un actor que ya ha terminado provoca que el método `act` se ejecute nuevamente. - -El tipo `Reactor` define el método `getState`, el cual retorna, como un miembro de la enumeración `Actor.State`, el estado actual de la ejecución del actor. Un actor que todavía no ha sido iniciado se encuentra en el estado `Actor.State.New`. Si el actor se está ejecutando pero no está esperando por ningún mensaje su estado será `Actor.State.Runnable`. En caso de que el actor haya sido suspendido mientras espera por un mensaje estará en el estado `Actor.State.Suspended`. Por último, un actor ya terminado se encontrará en el estado `Actor.State.Terminated`. - -#### Manejo de excepciones - -El miembro `exceptionHandler` permite llevar a cabo la definición de un manejador de excepciones que estará habilitado durante toda la vida del `Reactor`: - - def exceptionHandler: PartialFunction[Exception, Unit] - -Este manejador de excepciones (`exceptionHandler`) retorna una función parcial que se utiliza para gestionar excepciones que no hayan sido tratadas de ninguna otra manera. Siempre que una excepción se propague fuera del método `act` de un `Reactor` el manejador anterior será aplicado a dicha excepción, permitiendo al actor ejecutar código de limpieza antes de que se termine. Nótese que la visibilidad de `exceptionHandler` es `protected`. - -El manejo de excepciones mediante el uso de `exceptionHandler` encaja a la perfección con las estructuras de control utilizadas para programas con el método `react`. Siempre que una excepción es manejada por la función parcial retornada por `excepctionHandler`, la ejecución continua con la "closure" actual: - - loop { - react { - case Msg(data) => - if (cond) // process data - else throw new Exception("cannot process data") - } - } - -Assumiendo que `Reactor` sobreescribe el atributo `exceptionHandler`, tras el lanzamiento de una excepción en el cuerpo del método `react`, y una vez ésta ha sido gestionada, la ejecución continua con la siguiente iteración del bucle. - -### The ReplyReactor trait - -El trait `ReplyReactor` extiende `Reactor[Any]` y sobrescribe y/o añade los siguientes métodos: - -- El método `!` es sobrescrito para obtener una referencia al actor - actual (el emisor). Junto al mensaje actual, la referencia a dicho - emisor es enviada al buzón del actor receptor. Este último dispone de - acceso al emisor del mensaje mediante el uso del método `sender` (véase más abajo). - -- El método `forward` es sobrescrito para obtener una referencia al emisor - del mensaje que actualmente está siendo procesado. Junto con el mensaje - actual, esta referencia es enviada como el emisor del mensaje actual. - Como consuencia de este hecho, `forward` nos permite reenviar mensajes - en nombre de actores diferentes al actual. - -- El método (añadido) `sender` retorna el emisor del mensaje que está siendo - actualmente procesado. Puesto que un mensaje puede haber sido reenviado, - `sender` podría retornar un actor diferente al que realmente envió el mensaje. - -- El método (añadido) `reply` envía una respuesta al emisor del último mensaje. - `reply` también es utilizado para responder a mensajes síncronos o a mensajes - que han sido enviados mediante un "future" (ver más adelante). - -- El método (añadido) `!?` ofrece un *mecanismo síncrono de envío de mensajes*. - La invocación de `!?` provoca que el actor emisor del mensaje se bloquee hasta - que se recibe una respuesta, momento en el cual retorna dicha respuesta. Existen - dos variantes sobrecargadas. La versión con dos parámetros recibe un argumento - adicional que representa el tiempo de espera (medido en milisegundos) y su tipo - de retorno es `Option[Any]` en lugar de `Any`. En caso de que el emisor no - reciba una respuesta en el periodo de espera establecido, el método `!?` retornará - `None`; en otro caso retornará la respuesta recibida recubierta con `Some`. - -- Los métodos (añadidos) `!!` son similares al envío síncrono de mensajes en el sentido de - que el receptor puede enviar una respuesta al emisor del mensaje. Sin embargo, en lugar - de bloquear el actor emisor hasta que una respuesta es recibida, retornan una instancia de - `Future`. Esta última puede ser utilizada para recuperar la respuesta del receptor una - vez se encuentre disponible; asimismo puede ser utilizada para comprobar si la respuesta - está disponible sin la necesidad de bloquear el emisor. Existen dos versiones sobrecargadas. - La versión que acepta dos parámetros recibe un argumento adicional de tipo - `PartialFunction[Any, A]`. Esta función parcial es utilizada para realizar el post-procesado de - la respuesta del receptor. Básicamente, `!!` retorna un "future" que aplicará la anterior - función parcial a la repuesta (una vez recibida). El resultado del "future" es el resultado - de este post-procesado. - -- El método (añadido) `reactWithin` permite llevar a cabo la recepción de mensajes en un periodo - determinado de tiempo. En comparación con el método `react`, recibe un parámetro adicional, - `msec`, el cual representa el periodo de tiempo, expresado en milisegundos, hasta que el patrón `TIMEOUT` - es satisfecho (`TIMEOUT` es un "case object" presente en el paquete `scala.actors`). Ejemplo: - - reactWithin(2000) { - case Answer(text) => // process text - case TIMEOUT => println("no answer within 2 seconds") - } - -- El método `reactWithin` también permite realizar accesos no bloqueantes al buzón. Si - especificamos un tiempo de espera de 0 milisegundos, primeramente el buzón será escaneado - en busca de un mensaje que concuerde. En caso de que no exista ningún mensaje concordante - tras el primer escaneo, el patrón `TIMEOUT` será satisfecho. Por ejemplo, esto nos permite - recibir determinado tipo de mensajes donde unos tienen una prioridad mayor que otros: - - reactWithin(0) { - case HighPriorityMsg => // ... - case TIMEOUT => - react { - case LowPriorityMsg => // ... - } - } - - En el ejemplo anterior, el actor procesa en primer lugar los mensajes `HighPriorityMsg` aunque - exista un mensaje `LowPriorityMsg` más antiguo en el buzón. El actor sólo procesará mensajes - `LowPriorityMsg` en primer lugar en aquella situación donde no exista ningún `HighProrityMsg` - en el buzón. - -Adicionalmente, el tipo `ReplyActor` añade el estado de ejecución `Actor.State.TimedSuspended`. Un actor suspendido, esperando la recepción de un mensaje mediante el uso de `reactWithin` se encuentra en dicho estado. - -### El trait Actor - -El trait `Actor` extiende de `ReplyReactor` añadiendo y/o sobrescribiendo los siguientes miembros: - -- El método (añadido) `receive` se comporta del mismo modo que `react`, con la excepción - de que puede retornar un resultado. Este hecho se ve reflejado en la definición del tipo, - que es polimórfico en el tipo del resultado: `def receive[R](f: PartialFunction[Any, R]): R`. - Sin embargo, la utilización de `receive` hace que el uso del actor - sea más pesado, puesto que el hilo subyacente es bloqueado mientras - el actor está esperando por la respuesta. El hilo bloqueado no está - disponible para ejecutar otros actores hasta que la invocación del - método `receive` haya retornado. - -- El método (añadido) `link` permite a un actor enlazarse y desenlazarse de otro - actor respectivamente. El proceso de enlazado puede utilizarse para monitorizar - y responder a la terminación de un actor. En particular, el proceso de enlazado - afecta al comportamiento mostrado en la ejecución del método `exit` tal y como - se escribe en el la documentación del API del trait `Actor`. - -- El atributo `trapExit` permite responder a la terminación de un actor enlazado, - independientemente de los motivos de su terminación (es decir, carece de importancia - si la terminación del actor es normal o no). Si `trapExit` toma el valor cierto en - un actor, este nunca terminará por culpa de los actores enlazados. En cambio, siempre - y cuando uno de sus actores enlazados finalice, recibirá un mensaje de tipo `Exit`. - `Exit` es una "case class" que presenta dos atributos: `from` referenciando al actor - que termina y `reason` conteniendo los motivos de la terminación. - -#### Terminación y estados de ejecución - -Cuando la ejecución de un actor finaliza, el motivo de dicha terminación puede ser -establecida de manera explícita mediante la invocación de la siguiente variante -del método `exit`: - - def exit(reason: AnyRef): Nothing - -Un actor cuyo estado de terminación es diferente del símbolo `'normal` propaga -los motivos de su terminación a todos aquellos actores que se encuentren enlazados -a él. Si el motivo de la terminación es una excepción no controlada, el motivo de -finalización será una instancia de la "case class" `UncaughtException`. - -El trait `Actor` incluye dos nuevos estados de ejecución. Un actor que se encuentra -esperando la recepción de un mensaje mediante la utilización del método `receive` se -encuentra en el método `Actor.State.Blocked`. Un actor esperado la recepción de un -mensaje mediante la utilización del método `receiveWithin` se encuentra en el estado -`Actor.State.TimeBlocked`. - -## Estructuras de control - -El trait `Reactor` define una serie de estructuras de control que simplifican el mecanismo -de programación con la función sin retorno `react`. Normalmente, una invocación al método -`react` no retorna nunca. Si el actor necesita ejecutar código a continuación de la invocación -anterior, tendrá que pasar, de manera explícita, dicho código al método `react` o utilizar -algunas de las estructuras que encapsulan este comportamiento. - -La estructura de control más basica es `andThen`. Permite registrar una `closure` que será -ejecutada una vez el actor haya terminado la ejecución de todo lo demas. - - actor { - { - react { - case "hello" => // processing "hello" - }: Unit - } andThen { - println("hi there") - } - } - -Por ejemplo, el actor anterior imprime un saludo tras realizar el procesado -del mensaje `hello`. Aunque la invocación del método `react` no retorna, -podemos utilizar `andThen` para registrar el código encargado de imprimir -el saludo a continuación de la ejecución del actor. - -Nótese que existe una *atribución de tipo* a continuación de la invocación -de `react` (`:Unit`). Básicamente, nos permite tratar el resultado de -`react` como si fuese de tipo `Unit`, lo cual es legal, puesto que el resultado -de una expresión siempre se puede eliminar. Es necesario llevar a cabo esta operación -dado que `andThen` no puede ser un miembro del tipo `Unit`, que es el tipo del resultado -retornado por `react`. Tratando el tipo de resultado retornado por `react` como -`Unit` permite llevar a cabo la aplicación de una conversión implícita la cual -hace que el miembro `andThen` esté disponible. - -El API ofrece unas cuantas estructuras de control adicionales: - -- `loop { ... }`. Itera de manera indefinidia, ejecutando el código entre -las llaves en cada una de las iteraciones. La invocación de `react` en el -cuerpo del bucle provoca que el actor se comporte de manera habitual ante -la llegada de un nuevo mensaje. Posteriormente a la recepción del mensaje, -la ejecución continua con la siguiente iteración del bucle actual. - -- `loopWhile (c) { ... }`. Ejecuta el código entre las llaves mientras la -condición `c` tome el valor `true`. La invocación de `react` en el cuerpo -del bucle ocasiona el mismo efecto que en el caso de `loop`. - -- `continue`. Continua con la ejecución de la closure actual. La invocación -de `continue` en el cuerpo de un `loop`o `loopWhile` ocasionará que el actor -termine la iteración en curso y continue con la siguiente. Si la iteración en -curso ha sido registrada utilizando `andThen`, la ejecución continua con la -segunda "closure" pasada como segundo argumento a `andThen`. - -Las estructuras de control pueden ser utilizadas en cualquier parte del cuerpo -del método `act` y en los cuerpos de los métodos que, transitivamente, son -llamados por `act`. Aquellos actores creados utilizando la sintáxis `actor { ... }` -pueden importar las estructuras de control desde el objeto `Actor`. - -#### Futures - -Los traits `RepyActor` y `Actor` soportan operaciones de envío de mensajes -(métodos `!!`) que, de manera inmediata, retornan un *future*. Un *future*, -es una instancia del trait `Future` y actúa como un manejador que puede -ser utilizado para recuperar la respuesta a un mensaje "send-with-future". - -El emisor de un mensaje "send-with-future" puede esperar por la respuesta del -future *aplicando* dicha future. Por ejemplo, el envío de un mensaje mediante -`val fut = a !! msg` permite al emisor esperar por el resultado del future -del siguiente modo: `val res = fut()`. - -Adicionalmente, utilizando el método `isSet`, un `Future` puede ser consultado -de manera no bloqueante para comprobar si el resultado está disponible. - -Un mensaje "send-with-future" no es el único modo de obtener una referencia a -un future. Estos pueden ser creados utilizando el método `future`. En el siguiente -ejemplo, `body` se ejecuta de manera concurrente, retornando un future como -resultado. - - val fut = Future { body } - // ... - fut() // wait for future - -Lo que hace especial a los futures en el contexto de los actores es la posibilidad -de recuperar su resultado utilizando las operaciones estándar de actores de -recepción de mensajes como `receive`, etc. Además, es posible utilizar las operaciones -basadas en eventos `react`y `reactWithin`. Esto permite a un actor esperar por el -resultado de un future sin la necesidad de bloquear el hilo subyacente. - -Las operaciones de recepción basadas en actores están disponibles a través del -atributo `inputChannel` del future. Dado un future de tipo `Future[T]`, el tipo -de `inputChannel` es `InputChannel[T]`. Por ejemplo: - - val fut = a !! msg - // ... - fut.inputChannel.react { - case Response => // ... - } - -## Canales - -Los canales pueden ser utilizados para simplificar el manejo de mensajes -que presentan tipos diferentes pero que son enviados al mismo actor. La -jerarquía de canales se divide en `OutputChannel` e `InputChannel`. - -Los `OutputChannel` pueden ser utilizados para enviar mensajes. Un -`OutputChannel` `out` soporta las siguientes operaciones: - -- `out ! msg`. Envía el mensaje `msg` a `out` de manera asíncrona. Cuando `msg` - es enviado directamente a un actor se incluye un referencia al actor emisor - del mensaje. - -- `out forward msg`. Reenvía el mensaje `msg` a `out` de manera asíncrona. - El actor emisor se determina en el caso en el que `msg` es reenviado a - un actor. - -- `out.receiver`. Retorna el único actor que está recibiendo mensajes que están - siendo enviados al canal `out`. - -- `out.send(msg, from)`. Envía el mensaje `msg` a `out` de manera asíncrona, - proporcionando a `from` como el emisor del mensaje. - -Nótese que el trait `OutputChannel` tiene un parámetro de tipo que especifica el -tipo de los mensajes que pueden ser enviados al canal (utilizando `!`, `forward`, -y `send`). Este parámetro de tipo es contra-variante: - - trait OutputChannel[-Msg] - -Los actores pueden recibir mensajes de un `InputChannel`. Del mismo modo que -`OutputChannel`, el trait `InputChannel` presenta un parámetro de tipo que -especifica el tipo de mensajes que pueden ser recibidos por el canal. En este caso, -el parámetro de tipo es covariante: - - trait InputChannel[+Msg] - -Un `InputChannel[Msg]` `in` soportal las siguientes operaciones. - -- `in.receive { case Pat1 => ... ; case Patn => ... }` (y de manera similar, - `in.receiveWithin`) recibe un mensaje proveniente de `in`. La invocación - del método `receive` en un canal de entrada presenta la misma semántica - que la operación estándar de actores `receive`. La única diferencia es que - la función parcial pasada como argumento tiene tipo `PartialFunction[Msg, R]` - donde `R` es el tipo de retorno de `receive`. - -- `in.react { case Pat1 => ... ; case Patn => ... }` (y de manera similar, - `in.reactWithin`). Recibe un mensaje de `in` utilizando la operación basada en - eventos `react`. Del mismo modo que la operación `react` en actores, el tipo - de retorno es `Nothing`, indicando que las invocaciones de este método nunca - retornan. Al igual que la operación `receive` anterior, la función parcial - que se pasa como argumento presenta un tipo más específico: - - PartialFunction[Msg, Unit] - -### Creando y compartiendo canales - -Los canales son creados utilizando la clase concreta `Channel`. Esta clase extiende -de `InputChannel` y `OutputChannel`. Un canal pueden ser compartido haciendo dicho -canal visible en el ámbito de múltiples actores o enviándolo como mensaje. - -El siguiente ejemplo muestra la compartición mediante publicación en ámbitos: - - actor { - var out: OutputChannel[String] = null - val child = actor { - react { - case "go" => out ! "hello" - } - } - val channel = new Channel[String] - out = channel - child ! "go" - channel.receive { - case msg => println(msg.length) - } - } - -La ejecución de este ejemplo imprime la cadena "5" en la consola. Nótese que el -actor `child` únicamente tiene acceso a `out`, que es un `OutputChannel[String]`. -La referencia al canal, la cual puede ser utilizada para llevar a cabo la recepción -de mensajes, se encuentra oculta. Sin embargo, se deben tomar precauciones y -asegurarse que el canal de salida es inicializado con un canal concreto antes de que -`child` le envíe ningún mensaje. En el ejemplo que nos ocupa, esto es llevado a cabo -mediante el mensaje "go". Cuando se está recibiendo de `channel` utilizando el método -`channel.receive` podemos hacer uso del hecho que `msg` es de tipo `String`, y por -lo tanto tiene un miembro `length`. - -Una alternativa a la compartición de canales es enviarlos a través de mensajes. -El siguiente fragmento de código muestra un sencillo ejemplo de aplicación: - - case class ReplyTo(out: OutputChannel[String]) - - val child = actor { - react { - case ReplyTo(out) => out ! "hello" - } - } - - actor { - val channel = new Channel[String] - child ! ReplyTo(channel) - channel.receive { - case msg => println(msg.length) - } - } - -La "case class" `ReplyTo` es un tipo de mensajes que utilizamos para distribuir -una referencia a un `OutputChannel[String]`. Cuando el actor `child` recibe un -mensaje de tipo `ReplyTo` éste envía una cadena a su canal de salida. El segundo -actor recibe en el canal del mismo modo que anteriormente. - -## Planificadores - -Un `Reactor`(o una instancia de uno de sus subtipos) es ejecutado utilizando un -*planificador*. El trait `Reactor` incluye el miembro `scheduler` el cual retorna el -planificador utilizado para ejecutar sus instancias: - - def scheduler: IScheduler - -La plataforma de ejecución ejecuta los actores enviando tareas al planificador mediante -el uso de los métodos `execute` definidos en el trait `IScheduler`. La mayor parte -del resto de métodos definidos en este trait únicamente adquieren cierto protagonismo -cuando se necesita implementar un nuevo planificador desde cero; algo que no es necesario -en muchas ocasiones. - -Los planificadores por defecto utilizados para ejecutar instancias de `Reactor` y -`Actor` detectan cuando los actores han finalizado su ejecución. En el momento que esto -ocurre, el planificador se termina a si mismo (terminando con cualquier hilo que estuviera -en uso por parte del planificador). Sin embargo, algunos planificadores como el -`SingleThreadedScheduler` (definido en el paquete `scheduler`) necesita ser terminado de -manera explícita mediante la invocación de su método `shutdown`). - -La manera más sencilla de crear un planificador personalizado consisten en extender la clase -`SchedulerAdapter`, implementando el siguiente método abstracto: - - def execute(fun: => Unit): Unit - -Por norma general, una implementación concreata utilizaría un pool de hilos para llevar a cabo -la ejecución del argumento por nombre `fun`. - -## Actores remotos - -Esta sección describe el API de los actores remotos. Su principal interfaz es el objecto -`RemoteActor` definido en el paquete `scala.actors.remote`. Este objeto facilita el conjunto -de métodos necesarios para crear y establecer conexiones a instancias de actores remotos. En los -fragmentos de código que se muestran a continuación se asume que todos los miembros de -`RemoteActor` han sido importados; la lista completa de importaciones utilizadas es la siguiente: - - import scala.actors._ - import scala.actors.Actor._ - import scala.actors.remote._ - import scala.actors.remote.RemoteActor._ - -### Iniciando actores remotos - -Un actore remot es identificado de manera unívoca por un `Symbol`. Este símbolo -es único para la instancia de la máquina virual en la que se está ejecutando un -actor. Un actor remoto identificado con el nombre `myActor` puede ser creado del -siguiente modo. - - class MyActor extends Actor { - def act() { - alive(9000) - register('myActor, self) - // ... - } - } - -Nótese que el nombre únicamente puede ser registrado con un único actor al mismo tiempo. -Por ejemplo, para registrar el actor *A* como `'myActor` y posteriormente registrar otro -actor *B* como `'myActor`, debería esperar hasta que *A* haya finalizado. Este requisito -aplica a lo largo de todos los puertos, por lo que registrando a *B* en un puerto diferente -no sería suficiente. - -### Connecting to remote actors - -Establecer la conexión con un actor remoto es un proceso simple. Para obtener una referencia remota -a un actor remoto que está ejecutándose en la máquina `myMachine` en el puerto 8000 con el nombre -`'anActor`, tendremos que utilizar `select`del siguiente modo: - - val myRemoteActor = select(Node("myMachine", 8000), 'anActor) - -El actor retornado por `select` es de tipo `AbstractActor`, que proporciona esencialmente el mismo -interfaz que un actor normal, y por lo tanto es compatible con las habituales operaciones de envío -de mensajes: - - myRemoteActor ! "Hello!" - receive { - case response => println("Response: " + response) - } - myRemoteActor !? "What is the meaning of life?" match { - case 42 => println("Success") - case oops => println("Failed: " + oops) - } - val future = myRemoteActor !! "What is the last digit of PI?" - -Nótese que la operación `select` es perezosa; no inicializa ninguna conexión de red. Simplemente crea -una nueva instancia de `AbstractActor` que está preparada para iniciar una nueva conexión de red en el -momento en que sea necesario (por ejemplo cuando el método '!' es invocado). diff --git a/_overviews/core/actors.md b/_overviews/core/actors.md deleted file mode 100644 index 47b3e714b9..0000000000 --- a/_overviews/core/actors.md +++ /dev/null @@ -1,506 +0,0 @@ ---- -layout: singlepage-overview -title: The Scala Actors API - -partof: actors - -languages: [zh-cn, es] - -permalink: /overviews/core/:title.html ---- - -**Philipp Haller and Stephen Tu** - -## Introduction - -This guide describes the API of the `scala.actors` package of Scala 2.8/2.9. The organization follows groups of types that logically belong together. The trait hierarchy is taken into account to structure the individual sections. The focus is on the run-time behavior of the various methods that these traits define, thereby complementing the existing Scaladoc-based API documentation. - -NOTE: In Scala 2.10 the Actors library is deprecated and will be removed in future Scala releases. - -## The actor traits Reactor, ReplyReactor, and Actor - -### The Reactor trait - -`Reactor` is the super trait of all actor traits. Extending this trait allows defining actors with basic capabilities to send and receive messages. - -The behavior of a `Reactor` is defined by implementing its `act` method. The `act` method is executed once the `Reactor` is started by invoking `start`, which also returns the `Reactor`. The `start` method is *idempotent* which means that invoking it on an actor that has already been started has no effect. - -The `Reactor` trait has a type parameter `Msg` which indicates the type of messages that the actor can receive. - -Invoking the `Reactor`'s `!` method sends a message to the receiver. Sending a message using `!` is asynchronous which means that the sending actor does not wait until the message is received; its execution continues immediately. For example, `a ! msg` sends `msg` to `a`. All actors have a *mailbox* which buffers incoming messages until they are processed. - -The `Reactor` trait also defines a `forward` method. This method is inherited from `OutputChannel`. It has the same effect as the `!` method. Subtraits of `Reactor`, in particular the `ReplyReactor` trait, override this method to enable implicit reply destinations (see below). - -A `Reactor` receives messages using the `react` method. `react` expects an argument of type `PartialFunction[Msg, Unit]` which defines how messages of type `Msg` are handled once they arrive in the actor's mailbox. In the following example, the current actor waits to receive the string "Hello", and then prints a greeting: - - react { - case "Hello" => println("Hi there") - } - -Invoking `react` never returns. Therefore, any code that should run after a message has been received must be contained inside the partial function that is passed to `react`. For example, two messages can be received in sequence by nesting two invocations of `react`: - - react { - case Get(from) => - react { - case Put(x) => from ! x - } - } - -The `Reactor` trait also provides control structures which simplify programming with `react`. - -#### Termination and execution states - -The execution of a `Reactor` terminates when the body of its `act` method has run to completion. A `Reactor` can also terminate itself explicitly using the `exit` method. The return type of `exit` is `Nothing`, because `exit` always throws an exception. This exception is only used internally, and should never be caught. - -A terminated `Reactor` can be restarted by invoking its `restart` method. Invoking `restart` on a `Reactor` that has not terminated, yet, throws an `IllegalStateException`. Restarting a terminated actor causes its `act` method to be rerun. - -`Reactor` defines a method `getState` which returns the actor's current execution state as a member of the `Actor.State` enumeration. An actor that has not been started, yet, is in state `Actor.State.New`. An actor that can run without waiting for a message is in state `Actor.State.Runnable`. An actor that is suspended, waiting for a message is in state `Actor.State.Suspended`. A terminated actor is in state `Actor.State.Terminated`. - -#### Exception handling - -The `exceptionHandler` member allows defining an exception handler that is enabled throughout the entire lifetime of a `Reactor`: - - def exceptionHandler: PartialFunction[Exception, Unit] - -`exceptionHandler` returns a partial function which is used to handle exceptions that are not otherwise handled: whenever an exception propagates out of the body of a `Reactor`'s `act` method, the partial function is applied to that exception, allowing the actor to run clean-up code before it terminates. Note that the visibility of `exceptionHandler` is `protected`. - -Handling exceptions using `exceptionHandler` works well together with the control structures for programming with `react`. Whenever an exception has been handled using the partial function returned by `exceptionHandler`, execution continues with the current continuation closure. Example: - - loop { - react { - case Msg(data) => - if (cond) // process data - else throw new Exception("cannot process data") - } - } - -Assuming that the `Reactor` overrides `exceptionHandler`, after an exception thrown inside the body of `react` is handled, execution continues with the next loop iteration. - -### The ReplyReactor trait - -The `ReplyReactor` trait extends `Reactor[Any]` and adds or overrides the following methods: - -- The `!` method is overridden to obtain a reference to the current - actor (the sender); together with the actual message, the sender - reference is transferred to the mailbox of the receiving actor. The - receiver has access to the sender of a message through its `sender` - method (see below). - -- The `forward` method is overridden to obtain a reference to the - `sender` of the message that is currently being processed. Together - with the actual message, this reference is transferred as the sender - of the current message. As a consequence, `forward` allows - forwarding messages on behalf of actors different from the current - actor. - -- The added `sender` method returns the sender of the message that is - currently being processed. Given the fact that a message might have - been forwarded, `sender` may not return the actor that actually sent - the message. - -- The added `reply` method sends a message back to the sender of the - last message. `reply` is also used to reply to a synchronous message - send or a message send with future (see below). - -- The added `!?` methods provide *synchronous message sends*. Invoking - `!?` causes the sending actor to wait until a response is received - which is then returned. There are two overloaded variants. The - two-parameter variant takes in addition a timeout argument (in - milliseconds), and its return type is `Option[Any]` instead of - `Any`. If the sender does not receive a response within the - specified timeout period, `!?` returns `None`, otherwise it returns - the response wrapped in `Some`. - -- The added `!!` methods are similar to synchronous message sends in - that they allow transferring a response from the receiver. However, - instead of blocking the sending actor until a response is received, - they return `Future` instances. A `Future` can be used to retrieve - the response of the receiver once it is available; it can also be - used to find out whether the response is already available without - blocking the sender. There are two overloaded variants. The - two-parameter variant takes in addition an argument of type - `PartialFunction[Any, A]`. This partial function is used for - post-processing the receiver's response. Essentially, `!!` returns a - future which applies the partial function to the response once it is - received. The result of the future is the result of this - post-processing. - -- The added `reactWithin` method allows receiving messages within a - given period of time. Compared to `react` it takes an additional - parameter `msec` which indicates the time period in milliseconds - until the special `TIMEOUT` pattern matches (`TIMEOUT` is a case - object in package `scala.actors`). Example: - - reactWithin(2000) { - case Answer(text) => // process text - case TIMEOUT => println("no answer within 2 seconds") - } - - The `reactWithin` method also allows non-blocking access to the - mailbox. When specifying a time period of 0 milliseconds, the - mailbox is first scanned to find a matching message. If there is no - matching message after the first scan, the `TIMEOUT` pattern - matches. For example, this enables receiving certain messages with a - higher priority than others: - - reactWithin(0) { - case HighPriorityMsg => // ... - case TIMEOUT => - react { - case LowPriorityMsg => // ... - } - } - - In the above example, the actor first processes the next - `HighPriorityMsg`, even if there is a `LowPriorityMsg` that arrived - earlier in its mailbox. The actor only processes a `LowPriorityMsg` - *first* if there is no `HighPriorityMsg` in its mailbox. - -In addition, `ReplyReactor` adds the `Actor.State.TimedSuspended` execution state. A suspended actor, waiting to receive a message using `reactWithin` is in state `Actor.State.TimedSuspended`. - -### The Actor trait - -The `Actor` trait extends `ReplyReactor` and adds or overrides the following members: - -- The added `receive` method behaves like `react` except that it may - return a result. This is reflected in its type, which is polymorphic - in its result: `def receive[R](f: PartialFunction[Any, R]): R`. - However, using `receive` makes the actor more heavyweight, since - `receive` blocks the underlying thread while the actor is suspended - waiting for a message. The blocked thread is unavailable to execute - other actors until the invocation of `receive` returns. - -- The added `link` and `unlink` methods allow an actor to link and unlink - itself to and from another actor, respectively. Linking can be used - for monitoring and reacting to the termination of another actor. In - particular, linking affects the behavior of invoking `exit` as - explained in the API documentation of the `Actor` trait. - -- The `trapExit` member allows reacting to the termination of linked - actors independently of the exit reason (that is, it does not matter - whether the exit reason is `'normal` or not). If an actor's `trapExit` - member is set to `true`, this actor will never terminate because of - linked actors. Instead, whenever one of its linked actors terminates - it will receive a message of type `Exit`. The `Exit` case class has two - members: `from` refers to the actor that terminated; `reason` refers to - the exit reason. - -#### Termination and execution states - -When terminating the execution of an actor, the exit reason can be set -explicitly by invoking the following variant of `exit`: - - def exit(reason: AnyRef): Nothing - -An actor that terminates with an exit reason different from the symbol -`'normal` propagates its exit reason to all actors linked to it. If an -actor terminates because of an uncaught exception, its exit reason is -an instance of the `UncaughtException` case class. - -The `Actor` trait adds two new execution states. An actor waiting to -receive a message using `receive` is in state -`Actor.State.Blocked`. An actor waiting to receive a message using -`receiveWithin` is in state `Actor.State.TimedBlocked`. - -## Control structures - -The `Reactor` trait defines control structures that simplify programming -with the non-returning `react` operation. Normally, an invocation of -`react` does not return. If the actor should execute code subsequently, -then one can either pass the actor's continuation code explicitly to -`react`, or one can use one of the following control structures which -hide these continuations. - -The most basic control structure is `andThen`. It allows registering a -closure that is executed once the actor has finished executing -everything else. - - actor { - { - react { - case "hello" => // processing "hello" - }: Unit - } andThen { - println("hi there") - } - } - -For example, the above actor prints a greeting after it has processed -the `"hello"` message. Even though the invocation of `react` does not -return, we can use `andThen` to register the code which prints the -greeting as the actor's continuation. - -Note that there is a *type ascription* that follows the `react` -invocation (`: Unit`). Basically, it lets you treat the result of -`react` as having type `Unit`, which is legal, since the result of an -expression can always be dropped. This is necessary to do here, since -`andThen` cannot be a member of type `Nothing` which is the result -type of `react`. Treating the result type of `react` as `Unit` allows -the application of an implicit conversion which makes the `andThen` -member available. - -The API provides a few more control structures: - -- `loop { ... }`. Loops indefinitely, executing the code in braces in - each iteration. Invoking `react` inside the loop body causes the - actor to react to a message as usual. Subsequently, execution - continues with the next iteration of the same loop. - -- `loopWhile (c) { ... }`. Executes the code in braces while the - condition `c` returns `true`. Invoking `react` in the loop body has - the same effect as in the case of `loop`. - -- `continue`. Continues with the execution of the current continuation - closure. Invoking `continue` inside the body of a `loop` or - `loopWhile` will cause the actor to finish the current iteration and - continue with the next iteration. If the current continuation has - been registered using `andThen`, execution continues with the - closure passed as the second argument to `andThen`. - -The control structures can be used anywhere in the body of a `Reactor`'s -`act` method and in the bodies of methods (transitively) called by -`act`. For actors created using the `actor { ... }` shorthand the control -structures can be imported from the `Actor` object. - -#### Futures - -The `ReplyReactor` and `Actor` traits support result-bearing message -send operations (the `!!` methods) that immediately return a -*future*. A future, that is, an instance of the `Future` trait, is a -handle that can be used to retrieve the response to such a message -send-with-future. - -The sender of a message send-with-future can wait for the future's -response by *applying* the future. For example, sending a message using -`val fut = a !! msg` allows the sender to wait for the result of the -future as follows: `val res = fut()`. - -In addition, a `Future` can be queried to find out whether its result -is available without blocking using the `isSet` method. - -A message send-with-future is not the only way to obtain a -future. Futures can also be created from computations directly. -In the following example, the computation body is started to -run concurrently, returning a future for its result: - - val fut = Future { body } - // ... - fut() // wait for future - -What makes futures special in the context of actors is the possibility -to retrieve their result using the standard actor-based receive -operations, such as `receive` etc. Moreover, it is possible to use the -event-based operations `react` and `reactWithin`. This enables an actor to -wait for the result of a future without blocking its underlying -thread. - -The actor-based receive operations are made available through the -future's `inputChannel`. For a future of type `Future[T]`, its type is -`InputChannel[T]`. Example: - - val fut = a !! msg - // ... - fut.inputChannel.react { - case Response => // ... - } - -## Channels - -Channels can be used to simplify the handling of messages that have -different types but that are sent to the same actor. The hierarchy of -channels is divided into `OutputChannel`s and `InputChannel`s. - -`OutputChannel`s can be sent messages. An `OutputChannel` `out` -supports the following operations. - -- `out ! msg`. Asynchronously sends `msg` to `out`. A reference to the - sending actor is transferred as in the case where `msg` is sent - directly to an actor. - -- `out forward msg`. Asynchronously forwards `msg` to `out`. The - sending actor is determined as in the case where `msg` is forwarded - directly to an actor. - -- `out.receiver`. Returns the unique actor that is receiving messages - sent to the `out` channel. - -- `out.send(msg, from)`. Asynchronously sends `msg` to `out` supplying - `from` as the sender of the message. - -Note that the `OutputChannel` trait has a type parameter that specifies -the type of messages that can be sent to the channel (using `!`, -`forward`, and `send`). The type parameter is contravariant: - - trait OutputChannel[-Msg] - -Actors can receive messages from `InputChannel`s. Like `OutputChannel`, -the `InputChannel` trait has a type parameter that specifies the type of -messages that can be received from the channel. The type parameter is -covariant: - - trait InputChannel[+Msg] - -An `InputChannel[Msg]` `in` supports the following operations. - -- `in.receive { case Pat1 => ... ; case Patn => ... }` (and similarly, - `in.receiveWithin`). Receives a message from `in`. Invoking - `receive` on an input channel has the same semantics as the standard - `receive` operation for actors. The only difference is that the - partial function passed as an argument has type - `PartialFunction[Msg, R]` where `R` is the return type of `receive`. - -- `in.react { case Pat1 => ... ; case Patn => ... }` (and similarly, - `in.reactWithin`). Receives a message from `in` using the - event-based `react` operation. Like `react` for actors, the return - type is `Nothing`, indicating that invocations of this method never - return. Like the `receive` operation above, the partial function - passed as an argument has a more specific type: - - PartialFunction[Msg, Unit] - -### Creating and sharing channels - -Channels are created using the concrete `Channel` class. It extends both -`InputChannel` and `OutputChannel`. A channel can be shared either by -making the channel visible in the scopes of multiple actors, or by -sending it in a message. - -The following example demonstrates scope-based sharing. - - actor { - var out: OutputChannel[String] = null - val child = actor { - react { - case "go" => out ! "hello" - } - } - val channel = new Channel[String] - out = channel - child ! "go" - channel.receive { - case msg => println(msg.length) - } - } - -Running this example prints the string `"5"` to the console. Note that -the `child` actor has only access to `out` which is an -`OutputChannel[String]`. The `channel` reference, which can also be used -to receive messages, is hidden. However, care must be taken to ensure -the output channel is initialized to a concrete channel before the -`child` sends messages to it. This is done using the `"go"` message. When -receiving from `channel` using `channel.receive` we can make use of the -fact that `msg` is of type `String`; therefore, it provides a `length` -member. - -An alternative way to share channels is by sending them in -messages. The following example demonstrates this. - - case class ReplyTo(out: OutputChannel[String]) - - val child = actor { - react { - case ReplyTo(out) => out ! "hello" - } - } - - actor { - val channel = new Channel[String] - child ! ReplyTo(channel) - channel.receive { - case msg => println(msg.length) - } - } - -The `ReplyTo` case class is a message type that we use to distribute a -reference to an `OutputChannel[String]`. When the `child` actor receives a -`ReplyTo` message it sends a string to its output channel. The second -actor receives a message on that channel as before. - -## Schedulers - -A `Reactor` (or an instance of a subtype) is executed using a -*scheduler*. The `Reactor` trait introduces the `scheduler` member which -returns the scheduler used to execute its instances: - - def scheduler: IScheduler - -The run-time system executes actors by submitting tasks to the -scheduler using one of the `execute` methods defined in the `IScheduler` -trait. Most of the trait's other methods are only relevant when -implementing a new scheduler from scratch, which is rarely necessary. - -The default schedulers used to execute instances of `Reactor` and `Actor` -detect the situation when all actors have finished their -execution. When this happens, the scheduler shuts itself down -(terminating any threads used by the scheduler). However, some -schedulers, such as the `SingleThreadedScheduler` (in package `scheduler`) -have to be shut down explicitly by invoking their `shutdown` method. - -The easiest way to create a custom scheduler is by extending -`SchedulerAdapter`, implementing the following abstract member: - - def execute(fun: => Unit): Unit - -Typically, a concrete implementation would use a thread pool to -execute its by-name argument `fun`. - -## Remote Actors - -This section describes the remote actors API. Its main interface is -the `RemoteActor` object in package `scala.actors.remote`. This object -provides methods to create and connect to remote actor instances. In -the code snippets shown below we assume that all members of -`RemoteActor` have been imported; the full list of imports that we use -is as follows: - - import scala.actors._ - import scala.actors.Actor._ - import scala.actors.remote._ - import scala.actors.remote.RemoteActor._ - -### Starting remote actors - -A remote actor is uniquely identified by a [`Symbol`](https://www.scala-lang.org/api/current/scala/Symbol.html). This symbol is -unique to the JVM instance on which the remote actor is executed. A -remote actor identified with name `'myActor` can be created as follows. - - class MyActor extends Actor { - def act() { - alive(9000) - register('myActor, self) - // ... - } - } - -Note that a name can only be registered with a single (alive) actor at -a time. For example, to register an actor *A* as `'myActor`, and then -register another actor *B* as `'myActor`, one would first have to wait -until *A* terminated. This requirement applies across all ports, so -simply registering *B* on a different port as *A* is not sufficient. - -### Connecting to remote actors - -Connecting to a remote actor is just as simple. To obtain a remote -reference to a remote actor running on machine `myMachine`, on port -8000, with name `'anActor`, use `select` in the following manner: - - val myRemoteActor = select(Node("myMachine", 8000), 'anActor) - -The actor returned from `select` has type `AbstractActor` which provides -essentially the same interface as a regular actor, and thus supports -the usual message send operations: - - myRemoteActor ! "Hello!" - receive { - case response => println("Response: " + response) - } - myRemoteActor !? "What is the meaning of life?" match { - case 42 => println("Success") - case oops => println("Failed: " + oops) - } - val future = myRemoteActor !! "What is the last digit of PI?" - -Note that `select` is lazy; it does not actually initiate any network -connections. It simply creates a new `AbstractActor` instance which is -ready to initiate a new network connection when needed (for instance, -when `!` is invoked). diff --git a/_zh-cn/overviews/core/actors.md b/_zh-cn/overviews/core/actors.md deleted file mode 100644 index 22f214532e..0000000000 --- a/_zh-cn/overviews/core/actors.md +++ /dev/null @@ -1,306 +0,0 @@ ---- -layout: singlepage-overview -title: The Scala Actors API - -partof: actors - -language: zh-cn ---- - -**Philipp Haller 和 Stephen Tu 著** - -## 简介 - -本指南介绍了Scala 2.8和2.9中`scala.actors`包的API。这个包的内容因为逻辑上相通,所以放到了同一个类型的包内。这个trait在每个章节里面都会有所涉及。这章的重点在于这些traits所定义的各种方法在运行状态时的行为,由此来补充现有的Scala基础API。 - -注意:在Scala 2.10版本中这个Actors库将是过时的,并且在未来Scala发布的版本中将会被移除。 - -## Actor trait:Reactor, ReplyReactor和Actor - -### Reactor trait - -Reactor 是所有`actor trait`的父级trait。扩展这个trait可以定义actor,其具有发送和接收消息的基本功能。 - -Reactor的行为通过实现其act方法来定义。一旦调用start方法启动Reactor,这个act方法便会执行,并返回这个Reactor对象本身。start方法是具有等幂性的,也就是说,在一个已经启动了的actor对象上调用它(start方法)是没有作用的。 - -Reactor trait 有一个Msg 的类型参数,这个参数指明这个actor所能接收的消息类型。 - -调用Reactor的!方法来向接收者发送消息。用!发送消息是异步的,这样意味着不会等待消息被接收——它在发送消息后便立刻往下执行。例如:`a ! msg`表示向`a`发送`msg`。每个actor都有各自的信箱(mailbox)作为缓冲来存放接收到的消息,直至这些消息得到处理。 - -Reactor trait中也定义了一个forward方法,这个方法继承于OutputChannel。它和!(感叹号,发送方法)有同样的作用。Reactor的SubTrait(子特性)——特别是`ReplyReactor trait`——覆写了此方法,使得它能够隐式地回复目标。(详细地看下面的介绍) - -一个Reactor用react方法来接收消息。react方法需要一个PartialFunction[Msg, Unit]类型的参数,当消息到达actor的邮箱之后,react方法根据这个参数来确定如何处理消息。在下面例子中,当前的actor等待接收一个“Hello”字符串,然后打印一句问候。 - - react { - case "Hello" => println("Hi there") - } - -调用react没有返回值。因此,在接收到一条消息后,任何要执行的代码必须被包含在传递给react方法的偏函数(partial function)中。举个例子,通过嵌套两个react方法调用可以按顺序接收到两条消息: - - react { - case Get(from) => - react { - case Put(x) => from ! x - } - } - -Reactor trait 也提供了控制结构,简化了react方法的代码。 - -### 终止和执行状态 - -当Reactor的act方法完整执行后, Reactor则随即终止执行。Reactor也可以显式地使用exit方法来终止自身。exit方法的返回值类型为Nothing,因为它总是会抛出异常。这个异常仅在内部使用,并且不应该去捕捉这个异常。 - -一个已终止的Reactor可以通过它的restart方法使它重新启动。对一个未终止的Reactor调用restart方法则会抛出`IllegalStateException`异常。重新启动一个已终止的actor则会使它的act方法重新运行。 - -Reactor定义了一个getState方法,这个方法可以将actor当前的运行状态作为Actor.State枚举的一个成员返回。一个尚未运行的actor处于`Actor.State.New`状态。一个能够运行并且不在等待消息的actor处于`Actor.State.Runnable`状态。一个已挂起,并正在等待消息的actor处于`Actor.State.Suspended`状态。一个已终止的actor处于`Actor.State.Terminated`状态。 - -### 异常处理 - -exceptionHandler成员允许定义一个异常处理程序,其在Reactor的整个生命周期均可用。 - - def exceptionHandler: PartialFunction[Exception, Unit] - -exceptionHandler返回一个偏函数,它用来处理其他没有被处理的异常。每当一个异常被传递到Reactor的act方法体之外时,这个成员函数就被应用到该异常,以允许这个actor在它结束前执行清理代码。注意:`exceptionHandler`的可见性为protected。 - -用exceptionHandler来处理异常并使用控制结构对与react的编程是非常有效的。每当exceptionHandler返回的偏函数处理完一个异常后,程序会以当前的后续闭包(continuation closure)继续执行。 - - loop { - react { - case Msg(data) => - if (cond) // 数据处理代码 - else throw new Exception("cannot process data") - } - } - -假设Reactor覆写了exceptionHandler,在处理完一个在react方法体内抛出的异常后,程序将会执行下一个循环迭代。 - -### ReplyReactor trait - -`ReplyReactor trait`扩展了`Reactor[Any]`并且增加或覆写了以下方法: - -!方法被覆写以获得一个当前actor对象(发送方)的引用,并且,这个发送方引用和实际的消息一起被传递到接收actor的信箱(mail box)中。接收方通过其sender方法访问消息的发送方(见下文)。 - -forward方法被覆写以获得一个引用,这个引用指向正在被处理的消息的发送方。引用和实际的消息一起作为当前消息的发送方传递。结果,forward方法允许代表不同于当前actor对象的actor对象转发消息。 - -增加的sender方法返回正被处理的消息的发送方。考虑到一个消息可能已经被转发,发送方可能不会返回实际发送消息的actor对象。 - -增加的reply方法向最后一个消息的发送方回复消息。reply方法也被用作回复一个同步消息发送或者一个使用future的消息发送(见下文)。 - -增加的!?方法提供同步消息发送。调用!?方法会引起发送方actor对象等待,直到收到一个响应,然后返回这个响应。重载的变量有两个。这个双参数变量需要额外的超时参数(以毫秒计),并且,它的返回类型是Option[Any]而不是Any。如果发送方在指定的超时期间没有收到一个响应,!?方法返回None,否则它会返回由Some包裹的响应。 - -增加的!!方法与同步消息发送的相似点在于,它们都允许从接收方传递一个响应。然而,它们返回Future实例,而不是阻塞发送中的actor对象直到接收响应。一旦Future对象可用,它可以被用来重新获得接收方的响应,还可以在不阻塞发送方的情况下,用于获知响应是否可用。重载的变量有两个。双参数变量需要额外的PartialFunction[Any,A]类型的参数。这个偏函数用于对接收方响应进行后处理。本质上,!!方法返回一个future对象,一旦响应被接收,这个future对象把偏函数应用于响应。future对象的结果就是后处理的结果。 - -增加的reactWithin方法允许在一段给定的时间段内接收消息。相对于react方法,这个方法需要一个额外的msec参数,用来指示在这个时间段(以毫秒计)直到匹配指定的TIMEOUT模式为止(TIMEOUT是包scala.actors中的用例对象(case object))。例如: - -reactWithin(2000) { case Answer(text) => // process text case TIMEOUT => println("no answer within 2 seconds") } - -reactWithin方法也允许以非阻塞方式访问信箱。当指定一个0毫秒的时间段时,首先会扫描信箱以找到一个匹配消息。如果在第一次扫描后没有匹配的消息,这个TIMEOUT模式将会匹配。例如,这使得接收某些消息会比其他消息有较高的优先级: - -reactWithin(0) { case HighPriorityMsg => // ... case TIMEOUT => react { case LowPriorityMsg => // ... } } - -在上述例子中,即使在信箱里有一个先到达的低优先级的消息,actor对象也会首先处理下一个高优先级的消息。actor对象只有在信箱里没有高优先级消息时才会首先处理一个低优先级的消息。 - -另外,ReplyReactor 增加了`Actor.State.TimedSuspended`执行状态。一个使用`reactWithin`方法等待接收消息而挂起的actor对象,处在` Actor.State.TimedSuspended `状态。 - -### Actor trait - -Actor trait扩展了`ReplyReactor`并增加或覆写了以下成员: - -增加的receive方法的行为类似react方法,但它可以返回一个结果。这可以在它的类型上反映——它的结果是多态的:def receive[R](f: PartialFunction[Any, R]): R。然而,因为actor对象挂起并等待消息时,receive方法会阻塞底层线程(underlying thread),使用receive方法使actor对象变得更加重量级。直到receive方法的调用返回,阻塞的线程将不能够执行其他actor对象。 - -增加的link和unlink方法允许一个actor对象将自身链接到另一个actor对象,或将自身从另一个actor对象断开链接。链接可以用来监控或对另一个actor对象的终止做出反应。特别要注意的是,正如在Actor trait的API文档中的解释,链接影响调用exit方法的行为。 - -trapExit成员允许对链接的actor对象的终止做出反应而无关其退出的原因(即,无关是否正常退出)。如果一个actor对象的trapExit成员被设置为true,则这个actor对象会因链接的actor对象而永远不会终止。相反,每当其中一个链接的actor对象个终止了,它将会收到类型为Exit的消息。这个Exit case class 有两个成员:from指终止的actor对象;reason指退出原因。 - -### 终止和执行状态 - -当终止一个actor对象的执行时,可以通过调用以下exit方法的变体,显式地设置退出原因: - - def exit(reason: AnyRef): Nothing -当一个actor对象以符号'normal以外的原因退出,会向所有链接到它的atocr对象传递其退出原因。如果一个actor对象由于一个未捕获异常终止,它的退出原因则为一个UncaughtException case class的实例。 - -Actor trait增加了两个新的执行状态。使用receive方法并正在等待接收消息的actor处在`Actor.State.Blocked`状态。使用receiveWithin方法并正在等待接收消息的actor处在`Actor.State.TimedBlocked`状态。 - -## 控制结构 - -Reactor trait定义了控制结构,它简化了无返回的react操作的编程。一般来说,一个react方法调用并不返回。如果actor对象随后应当执行代码,那么,或者显式传递actor对象的后续代码给react方法,或者可以使用下述控制结构,达到隐藏这些延续代码的目的。 - -最基础的控制结构是andThen,它允许注册一个闭包。一旦actor对象的所有其他代码执行完毕,闭包就会被执行。 - - actor { - { - react { - case "hello" => // 处理 "hello" - }: Unit - } andThen { - println("hi there") - } - } - -例如,上述actor实例在它处理了“hello”消息之后,打印一句问候。虽然调用react方法不会返回,我们仍然可以使用andThen来注册这段输出问候的代码(作为actor的延续)。 - -注意:在react方法的调用(: Unit)中存在一种类型归属。总而言之,既然表达式的结果经常可以被忽略,react方法的结果就可以合法地作为Unit类型来处理。andThen方法无法成为Nothing类型(react方法的结果类型)的一个成员,所以在这里有必要这样做。把react方法的结果类型当作Unit,允许实现一个隐式转换的应用,这个隐式转换使得andThen成员可用。 - -API还提供一些额外的控制结构: - -loop { ... }。无限循环,在每一次迭代中,执行括号中的代码。调用循环体内的react方法,actor对象同样会对消息做出反应。而后,继续执行这个循环的下次迭代。 - -loopWhile (c) { ... }。当条件c返回true,执行括号中的代码。调用循环体中的react方法和使用loop时的效果一样。 - -continue。继续执行当前的接下来的后续闭包(continuation closure)。在loop或loopWhile循环体内调用continue方法将会使actor对象结束当前的迭代并继续执行下次迭代。如果使用andThen注册了当前的后续代码,这个闭包会作为第二个参数传给andThen,并以此继续执行。 - -控制结构可以在Reactor对象的act方法中,以及在act方法(传递地)调用的方法中任意处使用。对于用actor{...}这样的缩略形式创建的actor,控制结构可以从Actor对象导入。 - -### Future - -ReplyReactor和Actor trait支持发送带有结果的消息(!!方法),其立即返回一个future实例。一个future即Future trait的一个实例,即可以用来重新获取一个send-with-future消息的响应的句柄。 - -一个send-with-future消息的发送方可以通过应用future来等待future的响应。例如,使用val fut = a !! msg 语句发送消息,允许发送方等待future的结果。如:val res = fut()。 - -另外,一个Future可以在不阻塞的情况下,通过isSet方法来查询并获知其结果是否可用。 - -send-with-future的消息并不是获得future的唯一的方法。future也可以通过future方法计算而得。下述例子中,计算体会被并行地启动运行,并返回一个future实例作为其结果: - - val fut = Future { body } - // ... - fut() // 等待future - -能够通过基于actor的标准接收操作(例如receive方法等)来取回future的结果,使得future实例在actor上下文中变得特殊。此外,也能够通过使用基于事件的操作(react方法和ractWithin方法)。这使得一个actor实例在等待一个future实例结果时不用阻塞它的底层线程。 - -通过future的inputChannel,使得基于actor的接收操作方法可用。对于一个类型为`Future[T]`的future对象而言,它的类型是`InputChannel[T]`。例如: - - val fut = a !! msg - // ... - fut.inputChannel.react { - case Response => // ... - } - -## Channel(通道) - -channnel可以用来对发送到同一actor的不同类型消息的处理进行简化。channel的层级被分为OutputChannel和InputChannel。 - -OutputChannel可用于发送消息。OutputChannel的out方法支持以下操作。 - -out ! msg。异步地向out方法发送msg。当msg直接发送给一个actor,一个发送中的actor的引用会被传递。 - -out forward msg。异步地转发msg给out方法。当msg被直接转发给一个actor,发送中的actor会被确定。 - -out.receiver。返回唯一的actor,其接收发送到out channel(通道)的消息。 - -out.send(msg, from)。异步地发送msg到out,并提供from作为消息的发送方。 - -注意:OutputChannel trait有一个类型参数,其指定了可以被发送到channel(通道)的消息类型(使用!、forward和send)。这个类型参数是逆变的: - - trait OutputChannel[-Msg] - -Actor能够从InputChannel接收消息。就像OutputChannel,InputChannel trait也有一个类型参数,用于指定可以从channel(通道)接收的消息类型。这个类型参数是协变的: - - trait InputChannel[+Msg] - -An` InputChannel[Msg] `in支持下列操作。 - -in.receive { case Pat1 => ... ; case Patn => ... }(以及类似的 in.receiveWithin)。从in接收一个消息。在一个输入channel(通道)上调用receive方法和actor的标准receive操作具有相同的语义。唯一的区别是,作为参数被传递的偏函数具有PartialFunction[Msg, R]类型,此处R是receive方法的返回类型。 - -in.react { case Pat1 => ... ; case Patn => ... }(以及类似的in.reactWithin)通过基于事件的react操作,从in方法接收一个消息。就像actor的react方法,返回类型是Nothing。这意味着此方法的调用不会返回。就像之前的receive操作,作为参数传递的偏函数有一个更具体的类型:PartialFunction[Msg, Unit] - -### 创建和共享channel - -channel通过使用具体的Channel类创建。它同时扩展了InputChannel和OutputChannel。使channel在多个actor的作用域(Scope)中可见,或者将其在消息中发送,都可以实现channel的共享。 - -下面的例子阐述了基于作用域(scope)的共享。 - - actor { - var out: OutputChannel[String] = null - val child = actor { - react { - case "go" => out ! "hello" - } - } - val channel = new Channel[String] - out = channel - child ! "go" - channel.receive { - case msg => println(msg.length) - } - } - -运行这个例子将输出字符串“5”到控制台。注意:子actor对out(一个OutputChannel[String])具有唯一的访问权。而用于接收消息的channel的引用则被隐藏了。然而,必须要注意的是,在子actor向输出channel发送消息之前,确保输出channel被初始化到一个具体的channel。通过使用“go”消息来完成消息发送。当使用channel.receive来从channel接收消息时,因为消息是String类型的,可以使用它提供的length成员。 - -另一种共享channel的可行的方法是在消息中发送它们。下面的例子对此作了阐述。 - - case class ReplyTo(out: OutputChannel[String]) - - val child = actor { - react { - case ReplyTo(out) => out ! "hello" - } - } - - actor { - val channel = new Channel[String] - child ! ReplyTo(channel) - channel.receive { - case msg => println(msg.length) - } - } - -ReplyTo case class是一个消息类型,用于分派一个引用到OutputChannel[String]。当子actor接收一个ReplyTo消息时,它向它的输出channel发送一个字符串。第二个actor则像以前一样接收那个channel上的消息。 - -## Scheduler - -scheduler用于执行一个Reactor实例(或子类型的一个实例)。Reactor trait引入了scheduler成员,其返回常用于执行Reactor实例的scheduler。 - - def scheduler: IScheduler - -运行时系统通过使用在IScheduler trait中定义的execute方法之一,向scheduler提交任务来执行actor。只有在完整实现一个新的scheduler时(但没有必要),此trait的大多数其他方法才是相关的。 - -默认的scheduler常用于执行Reactor实例,而当所有的actor完成其执行时,Actor则会检测环境。当这发生时,scheduler把它自己关闭(终止scheduler使用的任何线程)。然而,一些scheduler,比如SingleThreadedScheduler(位于scheduler包)必须要通过调用它们的shutdown方法显式地关闭。 - -创建自定义scheduler的最简单方法是通过扩展SchedulerAdapter,实现下面的抽象成员: - - def execute(fun: => Unit): Unit - -典型情况下,一个具体的实现将会使用线程池来执行它的按名参数fun。 - -## 远程Actor - -这一段描述了远程actor的API。它的主要接口是scala.actors.remote包中的RemoteActor对象。这个对象提供各种方法来创建和连接到远程actor实例。在下面的代码段中我们假设所有的RemoteActor成员都已被导入,所使用的完整导入列表如下: - - import scala.actors._ - import scala.actors.Actor._ - import scala.actors.remote._ - import scala.actors.remote.RemoteActor._ - -### 启动远程Actor - -远程actor由一个Symbol唯一标记。在这个远程Actor所执行JVM上,这个符号对于JVM实例是唯一的。由名称'myActor标记的远程actor可按如下方法创建。 - - class MyActor extends Actor { - def act() { - alive(9000) - register('myActor, self) - // ... - } - } - -记住:一个名字一次只能标记到一个单独的(存活的)actor。例如,想要标记一个actorA为'myActor,然后标记另一个actorB为'myActor。这种情况下,必须等待A终止。这个要求适用于所有的端口,因此简单地将B标记到不同的端口来作为A是不能满足要求的。 - -### 连接到远程Actor - -连接到一个远程actor也同样简单。为了获得一个远程Actor的远程引用(运行于机器名为myMachine,端口为8000,名称为'anActor),可按下述方式使用select方法: - - val myRemoteActor = select(Node("myMachine", 8000), 'anActor) - -从select函数返回的actor具有类型AbstractActor,这个类型本质上提供了和通常actor相同的接口,因此支持通常的消息发送操作: - - myRemoteActor ! "Hello!" - receive { - case response => println("Response: " + response) - } - myRemoteActor !? "What is the meaning of life?" match { - case 42 => println("Success") - case oops => println("Failed: " + oops) - } - val future = myRemoteActor !! "What is the last digit of PI?" - -记住:select方法是惰性的,它不实际初始化任何网络连接。仅当必要时(例如,调用!时),它会单纯地创建一个新的,准备好初始化新网络连接的AbstractActor实例。