The actor support in GPars was originally inspired by the Actors library in Scala, but has since gone well
beyond what Scala offers as standard.

Actors allow for a message passing-based concurrency model: programs are collections of independent active
objects that exchange messages and have no mutable shared state.  Actors can help developers avoid issues
such as deadlock, live-lock and starvation, which are common problems for shared memory based approaches.
Actors are a way of leveraging the multi-core nature of today's hardware without all the problems
traditionally associated with shared-memory multi-threading, which is why programming languages such as
Erlang and Scala have taken up this model.

A nice article summarizing the key "concepts behind
actors":http://ruben.savanne.be/articles/concurrency-in-erlang-scala was written recently by Ruben
Vermeersch.  Actors always guarantee that *at most one thread processes the actor's body* at any one time
and also, under the covers, that the memory gets synchronized
each time a thread gets assigned to an actor so the actor's state *can be safely modified* by code in the body *without any other extra (synchronization or locking) effort* .
Ideally actor's code should *never be invoked* directly from outside so all the code of the actor class can only be executed by the thread
handling the last received message and so all the actor's code is *implicitly thread-safe* .
If any of the actor's methods is allowed to be called by other objects directly, the thread-safety guarantee for the actor's code and state are *no longer valid* .

h2. Types of actors

In general, you can find two types of actors in the wild - ones that hold *implicit state* and those, who don't. GPars gives you both options.
*Stateless* actors, represented in *GPars* by the _DynamicDispatchActor_ and the _ReactiveActor_ classes, keep no track of what messages have arrived previously.
You may thing of these as flat message handlers, which process messages as they come. Any state-based behavior has to be implemented by the user.

The *stateful* actors, represented in GPars by the _DefaultActor_ class (and previously also by the _AbstractPooledActor_ class), allow the user to handle implicit state directly.
After receiving a message the actor moves into a new state with different ways to handle future messages.
To give you an example, a freshly started actor may only accept some types of messages, e.g. encrypted messages for decryption,
only after it has received the encryption keys. The stateful actors allow to encode such dependencies directly in the structure
of the message-handling code.
Implicit state management, however, comes at a slight performance cost, mainly due to the lack of continuations support on JVM.

h2. Actor threading model

Since actors are detached from the system threads, a great number of actors can share a relatively small thread pool.
This can go as far as having many concurrent actors that share a single pooled thread. This architecture allows to avoid
some of the threading limitations of the JVM. In general, while the JVM can only give you a limited number of threads (typically around a couple of thousands),
the number of actors is only limited by the available memory. If an actor has no work to do, it doesn't consume threads.

Actor code is processed in chunks separated by quiet periods of waiting for new events (messages).
This can be naturally modeled through _continuations_ . As JVM doesn't support continuations directly, they have to be simulated in the actors frameworks,
which has slight impact on organization of the actors' code. However, the benefits in most cases outweigh the difficulties.

{code}
import groovyx.gpars.actor.Actor
import groovyx.gpars.actor.DefaultActor

class GameMaster extends DefaultActor {
    int secretNum

    void afterStart() {
        secretNum = new Random().nextInt(10)
    }

    void act() {
        loop {
            react { int num ->
                if (num > secretNum)
                reply 'too large'
                else if (num < secretNum)
                reply 'too small'
                else {
                    reply 'you win'
                    terminate()
                }
            }
        }
    }
}

class Player extends DefaultActor {
    String name
    Actor server
    int myNum

    void act() {
        loop {
            myNum = new Random().nextInt(10)
            server.send myNum
            react {
                switch (it) {
                    case 'too large': println "$name: $myNum was too large"; break
                    case 'too small': println "$name: $myNum was too small"; break
                    case 'you win': println "$name: I won $myNum"; terminate(); break
                }
            }
        }
    }
}

def master = new GameMaster().start()
def player = new Player(name: 'Player', server: master).start()

//this forces main thread to live until both actors stop
[master, player]*.join()
{code}
example by _Jordi Campos i Miralles, Departament de Matemàtica Aplicada i Anàlisi, MAiA Facultat de Matemàtiques, Universitat de Barcelona_

h1. Usage of Actors

Gpars provides consistent Actor APIs and DSLs. Actors in principal perform three specific operations - send messages, receive messages and create new actors. Although not specifically enforced by *GPars*
messages should be immutable or at least follow the *hands-off* policy when the sender never touches the messages after the message has been sent off.

h2. Sending messages

Messages can be sent to actors using the _send()_ method.

{code}
def passiveActor = Actors.actor{
    loop {
        react { msg -> println "Received: $msg"; }
    }
}
passiveActor.send 'Message 1'
passiveActor << 'Message 2'    //using the << operator
passiveActor 'Message 3'       //using the implicit call() method
{code}

Alternatively, the _<<_ operator or the implicit _call()_ method can be used. A family of _sendAndWait()_ methods is available to block the caller until a reply from the actor is available.
The _reply_ is returned from the _sendAndWait()_ method as a return value.
The _sendAndWait()_ methods may also return after a timeout expires or in case of termination of the called actor.

{code}
def replyingActor = Actors.actor{
    loop {
        react { msg ->
            println "Received: $msg";
            reply "I've got $msg"
        }
    }
}
def reply1 = replyingActor.sendAndWait('Message 4')
def reply2 = replyingActor.sendAndWait('Message 5', 10, TimeUnit.SECONDS)
use (TimeCategory) {
    def reply3 = replyingActor.sendAndWait('Message 6', 10.seconds)
}
{code}

The _sendAndContinue()_ method allows the caller to continue its processing while the supplied closure is waiting for a reply from the actor.

{code}
friend.sendAndContinue 'I need money!', {money -> pocket money}
println 'I can continue while my friend is collecting money for me'
{code}

The _sendAndPromise()_ method returns a _Promise_ (aka Future) to the final reply and so allows the caller to continue its processing
while the actor is handling the submitted message.

{code}
Promise loan = friend.sendAndPromise 'I need money!'
println 'I can continue while my friend is collecting money for me'
loan.whenBound {money -> pocket money}  //asynchronous waiting for a reply
println "Received ${loan.get()}"  //synchronous waiting for a reply
{code}

All _send()_ , _sendAndWait()_ or _sendAndContinue()_ methods will throw an exception if invoked on a non-active actor.

h2. Receiving messages

h3. Non-blocking message retrieval

Calling the _react()_ method, optionally with a timeout parameter, from within the actor's code will consume the next message from the actor's inbox,
potentially waiting, if there is no message to be processed immediately.

{code}
println 'Waiting for a gift'
react {gift ->
    if (myWife.likes gift) reply 'Thank you!'
}
{code}

Under the covers the supplied closure is not invoked directly, but scheduled for processing by any thread in the thread pool once
a message is available. After scheduling the current thread will then be detached from the actor and freed to process any other actor,
which has received a message already.

To allow detaching actors from the threads the _react()_ method demands the code to be written in a special *Continuation-style*.
{code}
Actors.actor {
    loop {
        println 'Waiting for a gift'
        react {gift ->
            if (myWife.likes gift) reply 'Thank you!'
            else {
                reply 'Try again, please'
                react {anotherGift ->
                    if (myChildren.like gift) reply 'Thank you!'
                }
                println 'Never reached'
            }
        }
        println 'Never reached'
    }
    println 'Never reached'
}
{code}

The _react()_ method has a special semantics to allow actors to be detached from threads when no messages are available in their mailbox.
Essentially, _react()_ schedules the supplied code (closure) to be executed upon next message arrival and returns.
The closure supplied to the _react()_ methods is the code where the computation should *continue* . Thus *continuation style* .

Since actor has to preserve the guarantee of at most one thread active within the actor's body, the next message cannot be handled
before the current message processing finishes. Typically, there shouldn't be a need to put code after calls to _react()_ .
Some actor implementations even enforce this, however, GPars does not for performance reasons.
The _loop()_ method allows iteration within the actor body. Unlike typical looping constructs, like _for_ or _while_ loops,
 _loop()_ cooperates with nested _react()_ blocks and will ensure looping across subsequent message retrievals.

h2. Sending replies

The _reply/replyIfExists_ methods are not only defined on the actors themselves, but for _AbstractPooledActor_ (not available in _DefaultActor_ , _DynamicDispatchActor_ nor _ReactiveActor_ classes) also on the processed messages themselves
upon their reception, which is particularly handy when handling multiple messages in a single call. In such cases _reply()_ invoked on the actor sends a reply to authors of all the currently processed message (the last one), whereas _reply()_ called on messages sends a reply to the author of the particular message only.

"See demo here":http://git.codehaus.org/gitweb.cgi?p=gpars.git;a=blob_plain;f=src/test/groovy/groovyx/gpars/samples/actors/stateful/DemoMultiMessage.groovy;hb=HEAD

h3. The sender property

Messages upon retrieval offer the sender property to identify the originator of the message. The property is available inside the Actor's closure:
{code}
react {tweet ->
    if (isSpam(tweet)) ignoreTweetsFrom sender
    sender.send 'Never write me again!'
}
{code}

h3. Forwarding

When sending a message, a different actor can be specified as the sender so that potential replies to the message will be forwarded to the specified actor and not to the actual originator.

{code}
def decryptor = Actors.actor {
    react {message ->
        reply message.reverse()
//        sender.send message.reverse()    //An alternative way to send replies
    }
}

def console = Actors.actor {  //This actor will print out decrypted messages, since the replies are forwarded to it
    react {
        println 'Decrypted message: ' + it
    }
}

decryptor.send 'lellarap si yvoorG', console  //Specify an actor to send replies to
console.join()
{code}

h2. Creating Actors

Actors share a *pool* of threads, which are dynamically assigned to actors when the actors need to *react* to messages sent to them. The threads are returned to back the pool once a message has been processed and the actor is idle waiting for some more messages to arrive.

For example, this is how you create an actor that prints out all messages that it receives.

{code}
def console = Actors.actor {
    loop {
        react {
            println it
        }
    }
}
{code}

Notice the _loop()_ method call, which ensures that the actor doesn't stop after having processed the first message.

Here's an example with a decryptor service, which can decrypt submitted messages and send the decrypted messages back to the originators.

{code}
final def decryptor = Actors.actor {
    loop {
        react {String message ->
            if ('stopService' == message) {
                println 'Stopping decryptor'
                stop()
            }
            else reply message.reverse()
        }
    }
}

Actors.actor {
    decryptor.send 'lellarap si yvoorG'
    react {
        println 'Decrypted message: ' + it
        decryptor.send 'stopService'
    }
}.join()
{code}

Here's an example of an actor that waits for up to 30 seconds to receive a reply to its message.

{code}
def friend = Actors.actor {
    react {
        //this doesn't reply -> caller won't receive any answer in time
        println it
        //reply 'Hello' //uncomment this to answer conversation
        react {
            println it
        }
    }
}

def me = Actors.actor {
    friend.send('Hi')
    //wait for answer 1sec
    react(1000) {msg ->
        if (msg == Actor.TIMEOUT) {
            friend.send('I see, busy as usual. Never mind.')
            stop()
        } else {
            //continue conversation
            println "Thank you for $msg"
        }
    }
}

me.join()
{code}

h2. Undelivered messages

Sometimes messages cannot be delivered to the target actor. When special action needs to be taken for undelivered messages, at actor termination all unprocessed messages from its queue have their _onDeliveryError()_ method called. The _onDeliveryError()_ method or closure defined on the message can, for example, send a notification back to the original sender of the message.

{code}
final DefaultActor me
me = Actors.actor {
    def message = 1

    message.metaClass.onDeliveryError = {->
        //send message back to the caller
        me << "Could not deliver $delegate"
    }

    def actor = Actors.actor {
        react {
            //wait 2sec in order next call in demo can be emitted
            Thread.sleep(2000)
            //stop actor after first message
            stop()
        }
    }

    actor << message
    actor << message

    react {
        //print whatever comes back
        println it
    }

}

me.join()
{code}

Alternatively the _onDeliveryError()_ method can be specified on the sender itself. The method can be added both dynamically

{code}
final DefaultActor me
me = Actors.actor {
    def message1 = 1
    def message2 = 2

    def actor = Actors.actor {
        react {
            //wait 2sec in order next call in demo can be emitted
            Thread.sleep(2000)
            //stop actor after first message
            stop()
        }
    }

    me.metaClass.onDeliveryError = {msg ->
        //callback on actor inaccessibility
        println "Could not deliver message $msg"
    }

    actor << message1
    actor << message2

    actor.join()

}

me.join()
{code}

and statically in actor definition:
{code}
class MyActor extends DefaultActor {
    public void onDeliveryError(msg) {
        println "Could not deliver message $msg"
    }
    ...
}
{code}

h2. Joining actors

Actors provide a _join()_ method to allow callers to wait for the actor to terminate. A variant accepting a timeout is also available. The Groovy _spread-dot_ operator comes in handy when joining multiple actors at a time.

{code}
def master = new GameMaster().start()
def player = new Player(name: 'Player', server: master).start()

[master, player]*.join()
{code}

h2. Conditional and counting loops

The _loop()_ method allows for either a condition or a number of iterations to be specified, optionally accompanied with a closure
to invoke once the loop finishes - _After Loop Termination Code Handler_ .

The following actor will loop three times to receive 3 messages and then prints out the maximum of the received messages.

{code}
final Actor actor = Actors.actor {
    def candidates = []
    def printResult = {-> println "The best offer is ${candidates.max()}"}

    loop(3, printResult) {
        react {
            candidates << it
        }
    }
}

actor 10
actor 30
actor 20
actor.join()
{code}

The following actor will receive messages until a value greater then 30 arrives.

{code}
final Actor actor = Actors.actor {
    def candidates = []
    final Closure printResult = {-> println "Reached best offer - ${candidates.max()}"}

    loop({-> candidates.max() < 30}, printResult) {
        react {
            candidates << it
        }
    }
}

actor 10
actor 20
actor 25
actor 31
actor 20
actor.join()
{code}

{note}
The _After Loop Termination Code Handler_ can use actor's _react{}_ but not _loop()_ .
{note}

{note}
_DefaultActor_ can be set to behave in a fair on non-fair (default) manner. Depending on the strategy chosen, the actor
either makes the thread available to other actors sharing the same parallel group (fair), or keeps the thread fot itself
until the message queue gets empty (non-fair). Generally, non-fair actors perform 2 - 3 times better than fair ones.

Use either the _fairActor()_ factory method or the actor's makeFair() method.

{note}

h2. Custom schedulers

Actors leverage the standard JDK concurrency library by default.  To provide a custom thread scheduler use the appropriate constructor parameter when creating a parallel group (PGroup class). The supplied scheduler will orchestrate threads in the group's thread pool.

Please also see the numerous "Actor Demos":http://git.codehaus.org/gitweb.cgi?p=gpars.git;a=tree;f=src/test/groovy/groovyx/gpars/samples;h=f9a751689a034a1d3de13c4874f4f4e839cb1026;hb=HEAD .
