Whenever the MailBox component has a message to process, it will invoke the receive method of Actor.
Let's demonstrate how to create various actor-model components and use them by creating a WelCome to Akka application with the help of the following steps:
- Download akka-actor_2.10.jar and scala-library-2.10.3.jar.
- Create DemoAkka as a Java Project and add the JARs as external dependencies.
- Create a POJO MyMessage in the com.packt.ch11.beans package, as shown in the following piece of code:
public class MyMessage implements Serializable { private String message; public MyMessage(String message) { this.message = message; } //getters and setters }
- Create an Actor1 class in the com.packt.ch11.actors package that will implement UntypedActor.
- Override the onReceive() method as follows:
public class Actor1 extends UntypedActor { public void onReceive(Object message) { if (message instanceof MyMessage) { System.out.println("The message is:" + ((MyMessage) message).getMessage()); } } }
The onReceive() method will be invoked by the Actor1 MailBox whenever MessageDispatcher makes a thread available and there is a message waiting in MessageQueue of MailBox.
- Create TestAkka with the main() function to test the code.
- Create a reference for ActorSystem with PacktSystem as its name.
- Create ActorRef that will point to Actor1.
- Send a message to ActorRef by invoking the tell method.
- Finally, shut down ActorSystem as follows:
public static void main(String[] args) { ActorSystem actorSystem = ActorSystem.create("PacktSystem"); ActorRef actorRef = actorSystem.actorOf(new
Props(Actor1.class), "actor1"); actorRef.tell(new MyMessage("Hello Welcome to Akka!")); try { Thread.sleep(3000); } catch (Exception e) { } actorSystem.stop(actorRef); actorSystem.shutdown(); }
- Execute the code and enjoy the output.
This is just an introductory demo to understand the difference in handling concurrency in OOPs and with Akka.