Learn Scala-actor with Lianle.

Source: Internet
Author: User
Tags case statement

  1. Each actor expands the actor class and provides the Act method;
  2. To send a message to the Web actor, you can use the actor! Message
  3. When the message is sent asynchronously, "forget it after you send it."
  4. To receive a message, the actor can call receive or react, which is usually done in a loop
  5. The Receive/react parameter is a block of code that consists of a case statement
  6. The status should not be shared between different actors. Always use messages to send data.
  7. Do not call the actor's method directly. Communicate through a message.
  8. Avoid synchronizing messages – that is, separating the sending and waiting responses.
  9. Different actors can share threads through react rather than receive, provided that the control flow of the message processor is simple enough.
  10. It's OK to let the actor hang up, provided you have other actors to monitor the actor's life and death. Use links to set up monitoring relationships.

Create and start actors

import scala.actor.Actorclass HiActor extends Actor {    def act (){        while (true) {            receive {                case"Hi" => println("Hello")            }        }    }}
valnew HiActoractor1.start()

If you need to create an actor temporarily instead of defining a class, the actor companion object has an actor method to create and start the actor:

import scala.actors.Actor._val actor2 = actor {    whhile(true) {        receive {        case"Hi" =>print("hello)        }    }}

Send Message
Use the actor definition! operator.

actor1!"Hi"

Receiving messages

使用case接收对象。

Send a message to another actor

These processing results need to be collected together when the operations are split into different actors to process the various parts of the problem in parallel.
The design options are as follows:
1. You can have a global actor.
2. The actor can be constructed as a reference with a pointer to one or more actors.
3. The actor can receive a message with a reference to another actor. Providing an actor reference in a request is a common practice, such as: actor ! Compute(data, continuation)
4. The actor can return a message to the sender. The Receive method sets the sender field to the sending of the current message.

Message Channel

Message channels are type-safe – you can only accept or send messages of a particular type.
You will not accidentally invoke the method of an actor through the message channel.

The message channel can be a outputchannel (with a! method), or it can be a inputchannel (with a receive or react method). The Channel class expands the Outputchannel and Inputchannel traits at the same time.

valnew Channel [Int] (someActor)
case class Compute(input: Seq[Int], result: OutputChannel[Int])class Conputer extends Actor {    public void act (){        while (true){            receive {                ...; out ! answer)            }        }    }}actor {    val channel = new Channel[Int]    ...    ...    computeActor ! Compute(input, channel)    channel.receive {        ...//我们已知x是一个int    }}

Synchronizing Messages and future

Actor can send a message and wait for a reply, with!? Operator:

val reply = account !? Deposit(1000)reply match {    case Balance(bal) => println("Current Balance: " + bal)}

The receiving party must return a message to the sender:

receive {    case Deposit(amount) => {balance += amount; sender ! Balance(balance)}}

You can use the Receivewithin method to specify how much time you want to wait:

actor {    worker ! Task(data, self)    1000) {        ...        case TimeOUT => log(...)    }}

can use!! To accept a future-. This is an object that will produce results when the results are available.

valreplayFutureaccount!!Deposit(100)
val replay = replyFuture()//这个调用将会阻塞,直到回复被发送。

the life cycle of the actor
The actor's Act method begins when the actor's Start method is invoked.

def act {    while(有更多事情要处理) {        receive {            ...        }    }}

The actor terminates execution in one of the following situations:
1. The Act method returns.
2. The Act method was terminated because of an exception.
3. Actor calls the Exit method.

Link multiple actors together

def act () {    link (master)    ...}

The connection is bidirectional.

Actor's design

Some suggestions:

  1. Avoid using shared state.
  2. Do not invoke the actor's method.
  3. Keep each actor simple.
  4. The context data is included in the message.
  5. Minimizes the response to the sender.
  6. Minimizes blocking calls.
  7. Use react whenever possible.
  8. Create a failure zone.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learn Scala-actor with Lianle.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.