(Quick Reference)

Creating an actor using a factory method

import static groovyx.gpars.actor.Actors.actor

def console = actor { loop { react { println it } }

Sub-classing the DefaultActor class

class CustomActor extends DefaultActor {
    @Override protected void act() {
        loop {
            react {
                println it
            }
        }
    }
}

def console=new CustomActor() console.start()

Sending messages

console.send('Message')
console << 'Message'
console.sendAndContinue 'Message', {reply -> println "I received reply: $reply"}
console.sendAndWait 'Message'

Timeouts

import static groovyx.gpars.actor.Actors.actor

def me = actor { friend.send('Hi') react(30.seconds) {msg -> if (msg == Actor.TIMEOUT) { friend.send('I see, busy as usual. Never mind.') stop() } else { //continue conversation } } }

me.join()

When a timeout expires when waiting for a message, the Actor.TIMEOUT message arrives instead. Also the onTimeout() handler is invoked, if present on the actor:

import static groovyx.gpars.actor.Actors.actor

def me = actor { delegate.metaClass.onTimeout = {-> friend.send('I see, busy as usual. Never mind.') stop() }

friend.send('Hi') react(30.seconds) { //continue conversation } }

me.join()

Actor groups

def coreActors = new NonDaemonPGroup(5)  //5 non-daemon threads pool
def helperActors = new DefaultPGroup(1)  //1 daemon thread pool

def priceCalculator = coreActors.actor { … }

def paymentProcessor = coreActors.actor { … }

def emailNotifier = helperActors.actor { … }

def cleanupActor = helperActors.actor { … }

//increase size of the core actor group coreActors.resize 6

//shutdown the group's pool once you no longer need the group to release resources helperActors.shutdown()

DynamicDispatchActor

final Actor actor = new DynamicDispatchActor({
    when {String msg -> println 'A String'; reply 'Thanks'}
    when {Double msg -> println 'A Double'; reply 'Thanks'}
    when {msg -> println 'A something ...'; reply 'What was that?'}
})
actor.start()

Reactor

import groovyx.gpars.actor.Actors

final def doubler = Actors.reactor { 2 * it }.start()