Last active
August 29, 2015 14:21
-
-
Save tmclnk/7c5e62cf10638a8d7581 to your computer and use it in GitHub Desktop.
GPARS Dynamic Dispatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovyx.gpars.actor.DynamicDispatchActor | |
import org.codehaus.groovy.runtime.NullObject | |
import groovy.time.TimeCategory | |
def actor = new DynamicDispatchActor(){ | |
private int counter = 0 | |
void onMessage(String message) { | |
counter += message.size() | |
println "Actor received string $message" | |
} | |
void onMessage(Integer message) { | |
counter += message | |
println "Actor received integer $message" | |
} | |
void onMessage(Object message) { | |
counter += 1 | |
println 'Actor received object' | |
} | |
void onMessage(NullObject message) { | |
'Actor received a null object. Sending back the current counter value.' | |
reply counter | |
} | |
} | |
actor.start() | |
actor.send(1) | |
actor.send("one") | |
// or the left-shift operator << can be used | |
actor << 2 | |
actor << "two" | |
// supposedly the implicit call() method can be used, but it | |
// failed for me :-( | |
//actor 3 | |
//actor "three" | |
// show that this IS async | |
println "There is no guarantee that this will print AFTER the actor prints its stuff!" | |
// in onMessage(NullObject) the Actor sends explicit reply, so we get a message back | |
assert actor.sendAndWait(null) == 9 | |
use(TimeCategory){ | |
println "Actor will print a response immediately, but this thread will wait" | |
println "for a reply. Because there is no reply in the actor, it will time out." | |
assert actor.sendAndWait("NOPE", 5.seconds) == null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment