|
1 |
| -# Actor Model |
| 1 | +--- |
| 2 | +title: "Actor Model Pattern in Java: Building Concurrent Systems with Elegance" |
| 3 | +shortTitle: Actor Model |
| 4 | +description: "Explore the Actor Model pattern in Java with real-world examples and practical implementation. Learn how to build scalable, message-driven systems using actors, messages, and asynchronous communication." |
| 5 | +category: Concurrency |
| 6 | +language: en |
| 7 | +tag: |
| 8 | + - Concurrency |
| 9 | + - Messaging |
| 10 | + - Isolation |
| 11 | + - Asynchronous |
| 12 | + - Distributed Systems |
| 13 | + - Actor Model |
| 14 | +--- |
2 | 15 |
|
3 |
| -## Intent |
| 16 | +## Also Known As |
4 | 17 |
|
5 |
| -The Actor Model is a concurrency pattern that treats "actors" as the fundamental units of computation. Each actor has its own state and behavior and interacts with other actors exclusively through message passing. |
| 18 | +- Message-passing concurrency |
| 19 | +- Actor-based concurrency |
6 | 20 |
|
7 |
| -## Explanation |
| 21 | +--- |
8 | 22 |
|
9 |
| -### Real-world Example |
| 23 | +## Intent of Actor Model Pattern |
10 | 24 |
|
11 |
| -Imagine a team of people (actors) working in an office. They don’t share the same brain (memory), but instead communicate by passing notes (messages). Each person reads one note at a time and responds accordingly. |
| 25 | +The Actor Model pattern enables the construction of highly concurrent, distributed, and fault-tolerant systems by using isolated components (actors) that interact exclusively through asynchronous message passing. |
12 | 26 |
|
13 |
| -### Problem |
| 27 | +--- |
14 | 28 |
|
15 |
| -Managing concurrent behavior in a safe and scalable way is difficult, especially with shared memory and race conditions. |
| 29 | +## Detailed Explanation of Actor Model Pattern with Real-World Examples |
16 | 30 |
|
17 |
| -### Solution |
| 31 | +### 📦 Real-world Example |
18 | 32 |
|
19 |
| -Encapsulate state and behavior within individual actors that communicate through asynchronous messages. |
| 33 | +Imagine a customer service system: |
| 34 | +- Each **customer support agent** is an **actor**. |
| 35 | +- Customers **send questions (messages)** to agents. |
| 36 | +- Each agent handles one request at a time and can **respond asynchronously** without interfering with other agents. |
20 | 37 |
|
21 |
| -## Class Diagram |
| 38 | +--- |
22 | 39 |
|
23 |
| - |
| 40 | +### 🧠 In Plain Words |
24 | 41 |
|
25 |
| -## Participants |
| 42 | +> "Actors are like independent workers that never share memory and only communicate through messages." |
26 | 43 |
|
27 |
| -- **Actor**: Base class that defines a mailbox and handles incoming messages sequentially. |
28 |
| -- **Message**: Represents communication between actors. |
29 |
| -- **ActorSystem**: Creates and manages actors. |
30 |
| -- **PrinterActor**: Sample actor that prints incoming messages. |
| 44 | +--- |
31 | 45 |
|
32 |
| -## Applicability |
| 46 | +### 📖 Wikipedia Says |
33 | 47 |
|
34 |
| -Use the Actor Model pattern when: |
| 48 | +> [Actor model](https://en.wikipedia.org/wiki/Actor_model) is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent computation. |
35 | 49 |
|
36 |
| -- You need a simple and safe way to handle concurrency. |
37 |
| -- You want to avoid thread synchronization issues like race conditions and deadlocks. |
38 |
| -- You want each object to process messages independently. |
| 50 | +--- |
39 | 51 |
|
40 |
| -## Example |
| 52 | +### 🧹 Architecture Diagram |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +--- |
| 57 | + |
| 58 | +## Programmatic Example of Actor Model Pattern in Java |
| 59 | + |
| 60 | +### Actor.java |
| 61 | + |
| 62 | +```java |
| 63 | +public abstract class Actor implements Runnable { |
| 64 | + |
| 65 | + @Setter @Getter private String actorId; |
| 66 | + private final BlockingQueue<Message> mailbox = new LinkedBlockingQueue<>(); |
| 67 | + private volatile boolean active = true; |
| 68 | + |
| 69 | + |
| 70 | + public void send(Message message) { |
| 71 | + mailbox.add(message); |
| 72 | + } |
| 73 | + |
| 74 | + public void stop() { |
| 75 | + active = false; |
| 76 | + } |
| 77 | + |
| 78 | + @Override |
| 79 | + public void run() { |
| 80 | + |
| 81 | + } |
| 82 | + |
| 83 | + protected abstract void onReceive(Message message); |
| 84 | +} |
| 85 | + |
| 86 | +``` |
| 87 | + |
| 88 | +### Message.java |
| 89 | + |
| 90 | +```java |
| 91 | + |
| 92 | +@AllArgsConstructor |
| 93 | +@Getter |
| 94 | +@Setter |
| 95 | +public class Message { |
| 96 | + private final String content; |
| 97 | + private final String senderId; |
| 98 | +} |
| 99 | +``` |
| 100 | + |
| 101 | +### ActorSystem.java |
| 102 | + |
| 103 | +```java |
| 104 | +public class ActorSystem { |
| 105 | + public void startActor(Actor actor) { |
| 106 | + String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID |
| 107 | + actor.setActorId(actorId); // assign the actor it's ID |
| 108 | + actorRegister.put(actorId, actor); // Register and save the actor with it's ID |
| 109 | + executor.submit(actor); // Run the actor in a thread |
| 110 | + } |
| 111 | + public Actor getActorById(String actorId) { |
| 112 | + return actorRegister.get(actorId); // Find by Id |
| 113 | + } |
| 114 | + |
| 115 | + public void shutdown() { |
| 116 | + executor.shutdownNow(); // Stop all threads |
| 117 | + } |
| 118 | +} |
| 119 | +``` |
| 120 | + |
| 121 | +### App.java |
41 | 122 |
|
42 | 123 | ```java
|
43 |
| -ActorSystem system = new ActorSystem(); |
44 |
| -Actor printer = system.actorOf(new PrinterActor()); |
| 124 | +public class App { |
| 125 | + public static void main(String[] args) { |
| 126 | + ActorSystem system = new ActorSystem(); |
| 127 | + Actor srijan = new ExampleActor(system); |
| 128 | + Actor ansh = new ExampleActor2(system); |
| 129 | + |
| 130 | + system.startActor(srijan); |
| 131 | + system.startActor(ansh); |
| 132 | + ansh.send(new Message("Hello ansh", srijan.getActorId())); |
| 133 | + srijan.send(new Message("Hello srijan!", ansh.getActorId())); |
| 134 | + |
| 135 | + Thread.sleep(1000); // Give time for messages to process |
| 136 | + |
| 137 | + srijan.stop(); // Stop the actor gracefully |
| 138 | + ansh.stop(); |
| 139 | + system.shutdown(); // Stop the actor system |
| 140 | + } |
| 141 | +} |
| 142 | +``` |
| 143 | + |
| 144 | +--- |
| 145 | + |
| 146 | +## When to Use the Actor Model Pattern in Java |
| 147 | + |
| 148 | +- When building **concurrent or distributed systems** |
| 149 | +- When you want **no shared mutable state** |
| 150 | +- When you need **asynchronous, message-driven communication** |
| 151 | +- When components should be **isolated and loosely coupled** |
| 152 | + |
| 153 | +--- |
| 154 | + |
| 155 | +## Actor Model Pattern Java Tutorials |
| 156 | + |
| 157 | +- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka) |
| 158 | +- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143) |
| 159 | + |
| 160 | +--- |
| 161 | + |
| 162 | +## Real-World Applications of Actor Model Pattern in Java |
| 163 | + |
| 164 | +- [Akka Framework](https://akka.io/) |
| 165 | +- [Erlang and Elixir concurrency](https://www.erlang.org/) |
| 166 | +- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/) |
| 167 | +- JVM-based game engines and simulators |
| 168 | + |
| 169 | +--- |
| 170 | + |
| 171 | +## Benefits and Trade-offs of Actor Model Pattern |
| 172 | + |
| 173 | +### ✅ Benefits |
| 174 | +- High concurrency support |
| 175 | +- Easy scaling across threads or machines |
| 176 | +- Fault isolation and recovery |
| 177 | +- Message ordering within actors |
| 178 | + |
| 179 | +### ⚠️ Trade-offs |
| 180 | +- Harder to debug due to asynchronous behavior |
| 181 | +- Slight performance overhead due to message queues |
| 182 | +- More complex to design than simple method calls |
| 183 | + |
| 184 | +--- |
| 185 | + |
| 186 | +## Related Java Design Patterns |
| 187 | + |
| 188 | +- [Command Pattern](../command) |
| 189 | +- [Mediator Pattern](../mediator) |
| 190 | +- [Event-Driven Architecture](../event-driven-architecture) |
| 191 | +- [Observer Pattern](../observer) |
| 192 | + |
| 193 | +--- |
45 | 194 |
|
46 |
| -printer.send(new Message("Hello Actor!", null)); |
47 |
| -printer.send(new Message("Another message", null)); |
| 195 | +## References and Credits |
48 | 196 |
|
49 |
| -Thread.sleep(1000); |
| 197 | +- *Programming Erlang*, Joe Armstrong |
| 198 | +- *Reactive Design Patterns*, Roland Kuhn |
| 199 | +- *The Actor Model in 10 Minutes*, [InfoQ Article](https://www.infoq.com/articles/actor-model/) |
| 200 | +- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html) |
50 | 201 |
|
51 |
| -((PrinterActor) printer).stop(); |
52 |
| -system.shutdown(); |
|
0 commit comments