Actor

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:

  1. Download akka-actor_2.10.jar and scala-library-2.10.3.jar.
  2. Create DemoAkka as a Java Project and add the JARs as external dependencies.
  3. 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 
} 
  1. Create an Actor1 class in the com.packt.ch11.actors package that will implement UntypedActor.
  2. 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.

  1. Create TestAkka with the main() function to test the code.
  2. Create a reference for ActorSystem with PacktSystem as its name.
  3. Create ActorRef that will point to Actor1.
  4. Send a message to ActorRef by invoking the tell method.
  5. 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(); }
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.64.132