Exercises
Working with untyped actors in Akka (a popular toolkit for building concurrent, distributed, and fault-tolerant systems on the JVM) is a great way to understand actor-based concurrency. Below are a few exercises that can help you practice working with untyped actors.
Exercise 1: Simple Ping-Pong
Objective: Implement two actors that send messages to each other.
- Actor 1 (PingActor): Sends a "Ping" message to Actor 2.
- Actor 2 (PongActor): Responds with a "Pong" message when it receives a "Ping".
- PingActor: Upon receiving "Pong", sends another "Ping" after a short delay.
Task:
- Implement the
PingActorandPongActorclasses. - Ensure the actors can send messages back and forth indefinitely.
Exercise 2: Counter Actor
Objective: Implement an actor that maintains a state.
- CounterActor: This actor should maintain an integer counter. It should handle the following messages:
- "Increment": Increments the counter by 1.
- "Decrement": Decrements the counter by 1.
- "Get": Replies with the current value of the counter.
Task:
- Implement the
CounterActor. - Create a main method where you create an instance of
CounterActor, send several messages to it, and print out the final counter value.
Exercise 3: Actor Hierarchy and Supervision
Objective: Understand actor hierarchy and supervision.
- ParentActor: This actor creates a child actor (
ChildActor). It supervises the child and restarts it when it fails. - ChildActor: This actor might occasionally throw an exception when it receives a "DoWork" message.
Task:
- Implement the
ParentActorandChildActor. - Set up supervision such that the
ParentActorrestarts theChildActorupon failure. - Create a scenario where the
ChildActoroccasionally fails, and observe how supervision works.
Exercise 4: Bank Account Actor
Objective: Model a simple bank account system using actors.
- BankAccountActor: This actor should handle the following messages:
- "Deposit(amount)": Adds the specified amount to the account balance.
- "Withdraw(amount)": Subtracts the specified amount if there are sufficient funds.
- "GetBalance": Replies with the current balance.
Task:
- Implement the
BankAccountActor. - Create a main method where you create an instance of
BankAccountActor, perform several deposits and withdrawals, and then print the final balance.
Exercise 5: Master-Worker Pattern
Objective: Implement a simple Master-Worker pattern using actors.
- MasterActor: Distributes tasks among several worker actors and collects the results.
- WorkerActor: Performs a computation and returns the result to the master.
Task:
- Implement the
MasterActorandWorkerActor. - The
MasterActorshould divide a list of integers into sublists and send each sublist to a worker actor to compute the sum. - Collect and print the final sum of all integers.