Actor Model
The Actor Model provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management, making it easier to write correct concurrent and parallel systems.
Continuing from my last concurrency post we will try to solve the word counting problem using Actors.
I am assuming you know how akka actors work. So if you don’t already know you can read more on Akka.
I will try and solve the problem in three languages, Java, Scala and Kotlin and we will see how different the code looks. And which one we like the most.
Problem Statement - Word Counting
We will write a program to get files and word count in each file from a given directory. The program will essentially do the following things.
- Get all files in the directory
- Count words in all the files
- Return a Map of file name and total word count.
Solution Strategy
Our solution is going to be simple. We will have two actors WordCountMaster
and WordCountWorker
.
WordCountMaster :
It does two tasks creates worker actors and collates results from the workers.
It accepts the following messages :
StartCounting message: Master actor receives this message and starts the task. It reads all files from the directory, creates the worker actors and tells each worker to start counting the words in each file.
WordCount message: On receipt of WordCount message from each worker, the master collates the result and responds with the result to the original sender.
WordCountWorker :
Works on individual files to count the number of words in the file. Starts the task on receiving FileToCount message.
Java Implementation
- Test
- Implementation
Scala Implementation
- Test
- Implementation
Kotlin Implementation
Kotlin is a new programming language from JetBrains.
It fixes a lot of issues we have with java - https://kotlinlang.org/docs/reference/comparison-to-java.html
And I also meet a lot of people who are optimistic about kotlin adoption.
So I gave it a try and this is how the code looks. Definitely better than java, but Scala still stays my favourite.