DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Trending

  • Java’s Next Act: Native Speed for a Cloud-Native World
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Java Virtual Threads and Scaling
  1. DZone
  2. Coding
  3. Java
  4. Achieve Concurrency With Akka actors

Achieve Concurrency With Akka actors

This blog describes how we can avoid difficulties to acheive concurrency in Scala using Akka actors those we are having using Java concurrency model .

By 
Utkarsha Musmade user avatar
Utkarsha Musmade
·
May. 27, 20 · Analysis
Likes (3)
Comment
Save
Tweet
Share
5.9K Views

Join the DZone community and get the full member experience.

Join For Free

Java comes with a built-in multi-threading model based on shared data and locks. To use this model, you decide what data will be shared by multiple threads and mark as “synchronized” sections of the code that access the shared data.

It also provides a locking mechanism to ensure that only one thread can access the shared data at a time. Lock operations remove possibilities for race conditions but simultaneously add possibilities for deadlocks. In Scala, you can still use Java threads, but the “Actor model” is the preferred approach for concurrency. 

Actors provide a concurrency model that is easier to work with and can, therefore, help you avoid many of the difficulties of using Java’s native concurrency model.

Features of Actors

  1. When you instantiate an Actor in your code, Akka gives you an ActorRef, which you can use to send messages.
  2. Behind the scenes, Akka runs actors on real threads and many actors may share one thread.
  3. An Actor can create many actors called child actors.
  4. Actors interact only through asynchronous messages and never through direct method calls.
  5. Each actor has a unique address and a mailbox in which other actors can deliver messages.
  6. The actor will process all the messages in the mailbox in sequential order    (the implementation of the mailbox is FIFO).

Let’s see an example,

Java
 




x
30


 
1
 case class Add(num1: Int, num2: Int)
2
  case class Substract(num1: Int, num2: Int)
3
  case class Divide(num1: Int, num2: Int)
4

          
5
  class Calculator extends Actor {
6

          
7
    def receive = {
8
      case Add(num1, num2) => context.actorOf(Props[Addition]) ! Add(num1, num2)
9
      case Substract(num1, num2) => context.actorOf(Props[Substraction]) ! Substract(num1, num2)
10
      case Divide(num1, num2) => context.actorOf(Props[Division]) ! Divide(num1, num2)
11
    }
12
  }
13

          
14
  class Addition extends Actor {
15
    def receive = {
16
      case Add(num1, num2) => println(num1 + num2)
17
    }
18
  }
19

          
20
  class Substraction extends Actor {
21
    def receive = {
22
      case Substract(num1, num2) => println(num1 - num2)
23
    }
24
  }
25

          
26
  class Division extends Actor {
27
    def receive = {
28
      case Divide(num1, num2) => println(num1 % num2)
29
    }
30
  }


We have a simple example of a calculator that performs three operations: addition, subtraction and division, and also have created three messages and has taken child actors accordingly. Now let's create the main method: 

Java
 




xxxxxxxxxx
1


 
1
val system = ActorSystem("Demo")
2
val actor1 = system.actorOf(Props[Calculator])
3
println("Started Calculating.....")
4
println("Addition")
5
actor1 ! Add(2, 3)
6
println("Substraction")
7
actor1 ! Substract(3, 2)
8
println("Divide")
9
actor1 ! Divide(2,3)


And the output of this is as follows: 

Plain Text
 




xxxxxxxxxx
1


 
1
Started Calculating.....
2
Addition
3
Substraction
4
Divide
5
5
6
1
7
2


If you observe the output, the main actor sends all three messages to the actor Calculator (parent actor) at the same time and all three operations performed asynchronously.

Handling shared variables and Non-Blocking

If two actors send a message to the same actor to access the same resource at the same time, the receiving actor will keep that message inside the mailbox and will execute those messages sequentially.

The sender thread does not get blocked to wait for a return value when it sends a message to another actor.

You need not worry about synchronization in a multi-threaded environment because of the fact that all the messages are processed sequentially and actors don’t share each other’s data.

In the below diagram, while Actor B is working on the A’s message, C’s message will sit in the mailbox. After completing the execution of A’s message, it will start execution of C’s message.

Shared variables

Handling Failures

Akka provides supervision strategies to handle errors when an actor fails due to any reason while executing a parent actor who supervises and handles the failure.

There are two supervision strategies,

  •  OneForOne - handled case applies only for a failed child.
  •  actorAllForOne - handled case applies to all siblings.

If we pass the following message to above Calculator actor then it will throw an exception:

Java
 




xxxxxxxxxx
1


 
1
actor1 ! Divide(2, 0)


This can be handled by adding following code snippet in parent actor:

Java
 




xxxxxxxxxx
1


 
1
override val supervisorStrategy = OneForOneStrategy(){
2
      case _: ArithmeticException => Resume
3
      case _ => Restart
4
}


I hope this blog was helpful.

Akka (toolkit)

Opinions expressed by DZone contributors are their own.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!