Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active October 10, 2015 16:58
Show Gist options
  • Save timyates/3722681 to your computer and use it in GitHub Desktop.
Save timyates/3722681 to your computer and use it in GitHub Desktop.
A Ping-Pong HotSwapped Untyped Akka Actor in Groovy
@Grab( 'com.typesafe.akka:akka-actor_2.10:2.3.2' )
@Grab( 'com.typesafe:config:1.2.0' )
import akka.actor.UntypedActor
import akka.japi.Procedure
import akka.actor.ActorSystem
import akka.actor.Props
import com.typesafe.config.ConfigFactory
class PingPongActor extends UntypedActor {
static final String PING = 'PING'
static final String PONG = 'PONG'
int count = 0
void onReceive( message ) {
if( message == PING ) {
println PING
count++
Thread.sleep 100
self.tell PONG, self
context.become( [ apply:{ msg ->
if( msg == PONG ) {
println PONG
count++
Thread.sleep 100
self.tell PING, self
context.unbecome()
}
} ] as Procedure )
if( count > 10 ) context.stop self
}
}
}
def cl = this.class.classLoader
ActorSystem.create( 'PingPong', ConfigFactory.load( cl ), cl ).with { system ->
system.actorOf( Props.create( PingPongActor ) ).with { actor ->
actor.tell PingPongActor.PING, actor
Thread.sleep 2000
shutdown()
}
}
@timyates
Copy link
Author

@timyates
Copy link
Author

PS: The reason for the ClassLoader jiggery-pokery is so it can be run in the Groovy Console. YMMV running outside of it.

@timyates
Copy link
Author

Just updated this to (I think) the latest version of akka

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment