Yusong's Blog Don't Panic

Actor Model

2017-09-01

Actor pattern is a high level approach to concurrent programming, it forces all accesses to an object to be isolated by default. Other method communicate with Actor by sending message to it.

Concurrent Programming in Java - Week3

Actors

One limitation of locks, and even isolated sections, is that, while many threads might correctly control the access to a shared object (e.g., by using object-based isolation) it only takes one thread that accesses the object directly to create subtle and hard-to-discover concurrency errors. The Actor model avoids this problem by forcing all accesses to an object to be isolated by default.

An Actor consists of a Mailbox, a set of Methods, and Local State. The Actor model is reactive, in that actors can only execute methods in response to messages; these methods can read/write local state and/or send messages to other actors.

https://en.wikipedia.org/wiki/Actor_model

Actor Examples

Sieve of Eratosthenes

how to use actors to implement a pipelined variant of the Sieve of Eratosthenes algorithm for generating prime numbers

public void process(final Object msg) {
  int candidate = (Integer) msg;
  // Check if the candidate is a non-multiple of the "local prime".
  // For example, localPrime = 2 in the Non-Mul-2 actor
  boolean nonMul = ((candidate % localPrime) != 0);
  // nothing needs to be done if nonMul = false
  if (nonMul) {
    if (nextActor == null) { 
      . . . // create & start new actor with candidate as its local prime
    }
    else nextActor.send(msg); // forward message to next actor
  } 
} // process

Time complexity:

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Computational_analysis

Producer-Consumer Problem with Unbounded Buffer

The key idea behind any actor-based solution is to think of all objects involved in the concurrent program as actors. in this case implies that producer tasks, consumer tasks, and the shared buffer should all be implemented as actors.

The next step is to establish the communication protocols among the actors.
A producer actor can simply send a message to the buffer actor whenever it has an item to produce.
The protocol for consumer actors is a bit more complicated. Our solution requires a consumer actor to send a message to the buffer actor whenever it is ready to process an item.

Bounded Buffer

the buffer actor needs to play a master role in the protocol by informing producer actors when they are permitted to send data. this is akin to the role played by the buffer/master actor with respect to consumer actors, even in the unbounded buffer case (in which the consumer actor informed the buffer actor when it is ready to consume an item). Now, the producer actor will only send data when requested to do so by the buffer actor.

https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem


Get update from Yusong's blog by Email on → Feedburner

Comments

Content