Skip to content

feat: Implement Actor Model pattern with automatic actor ID and communication with loose coupling #3251Actor model #3255

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
201 changes: 201 additions & 0 deletions actor-model/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
---
title: "Actor Model Pattern in Java: Building Concurrent Systems with Elegance"
shortTitle: Actor Model
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."
category: Concurrency
language: en
tag:
- Concurrency
- Messaging
- Isolation
- Asynchronous
- Distributed Systems
- Actor Model
---

## Also Known As

- Message-passing concurrency
- Actor-based concurrency

---

## Intent of Actor Model Pattern

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.

---

## Detailed Explanation of Actor Model Pattern with Real-World Examples

### 📦 Real-world Example

Imagine a customer service system:
- Each **customer support agent** is an **actor**.
- Customers **send questions (messages)** to agents.
- Each agent handles one request at a time and can **respond asynchronously** without interfering with other agents.

---

### 🧠 In Plain Words

> "Actors are like independent workers that never share memory and only communicate through messages."

---

### 📖 Wikipedia Says

> [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.

---

### 🧹 Architecture Diagram

![UML Class Diagram](./etc/Actor_Model_UML_Class_Diagram.png)

---

## Programmatic Example of Actor Model Pattern in Java

### Actor.java

```java
public abstract class Actor implements Runnable {

@Setter @Getter private String actorId;
private final BlockingQueue<Message> mailbox = new LinkedBlockingQueue<>();
private volatile boolean active = true;


public void send(Message message) {
mailbox.add(message);
}

public void stop() {
active = false;
}

@Override
public void run() {

}

protected abstract void onReceive(Message message);
}

```

### Message.java

```java

@AllArgsConstructor
@Getter
@Setter
public class Message {
private final String content;
private final String senderId;
}
```

### ActorSystem.java

```java
public class ActorSystem {
public void startActor(Actor actor) {
String actorId = "actor-" + idCounter.incrementAndGet(); // Generate a new and unique ID
actor.setActorId(actorId); // assign the actor it's ID
actorRegister.put(actorId, actor); // Register and save the actor with it's ID
executor.submit(actor); // Run the actor in a thread
}
public Actor getActorById(String actorId) {
return actorRegister.get(actorId); // Find by Id
}

public void shutdown() {
executor.shutdownNow(); // Stop all threads
}
}
```

### App.java

```java
public class App {
public static void main(String[] args) {
ActorSystem system = new ActorSystem();
Actor srijan = new ExampleActor(system);
Actor ansh = new ExampleActor2(system);

system.startActor(srijan);
system.startActor(ansh);
ansh.send(new Message("Hello ansh", srijan.getActorId()));
srijan.send(new Message("Hello srijan!", ansh.getActorId()));

Thread.sleep(1000); // Give time for messages to process

srijan.stop(); // Stop the actor gracefully
ansh.stop();
system.shutdown(); // Stop the actor system
}
}
```

---

## When to Use the Actor Model Pattern in Java

- When building **concurrent or distributed systems**
- When you want **no shared mutable state**
- When you need **asynchronous, message-driven communication**
- When components should be **isolated and loosely coupled**

---

## Actor Model Pattern Java Tutorials

- [Baeldung – Akka with Java](https://www.baeldung.com/java-akka)
- [Vaughn Vernon – Reactive Messaging Patterns](https://vaughnvernon.co/?p=1143)

---

## Real-World Applications of Actor Model Pattern in Java

- [Akka Framework](https://akka.io/)
- [Erlang and Elixir concurrency](https://www.erlang.org/)
- [Microsoft Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/)
- JVM-based game engines and simulators

---

## Benefits and Trade-offs of Actor Model Pattern

### ✅ Benefits
- High concurrency support
- Easy scaling across threads or machines
- Fault isolation and recovery
- Message ordering within actors

### ⚠️ Trade-offs
- Harder to debug due to asynchronous behavior
- Slight performance overhead due to message queues
- More complex to design than simple method calls

---

## Related Java Design Patterns

- [Command Pattern](../command)
- [Mediator Pattern](../mediator)
- [Event-Driven Architecture](../event-driven-architecture)
- [Observer Pattern](../observer)

---

## References and Credits

- *Programming Erlang*, Joe Armstrong
- *Reactive Design Patterns*, Roland Kuhn
- *The Actor Model in 10 Minutes*, [InfoQ Article](https://www.infoq.com/articles/actor-model/)
- [Akka Documentation](https://doc.akka.io/docs/akka/current/index.html)

Binary file added actor-model/etc/Actor_Model_UML_Class_Diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 35 additions & 0 deletions actor-model/etc/actor-model.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@startuml actor-model

title Actor Model - UML Class Diagram

class ActorSystem {
+actorOf(actor: Actor): Actor
+shutdown(): void
}

class Actor {
-mailbox: BlockingQueue<Message>
-active: boolean
+send(message: Message): void
+stop(): void
+run(): void
#onReceive(message: Message): void
}

class ExampleActor {
+onReceive(message: Message): void
}

class Message {
-content: String
-sender: Actor
+getContent(): String
+getSender(): Actor
}

ActorSystem --> Actor : creates
Actor <|-- ExampleActor : extends
Actor --> Message : processes
ExampleActor --> Message : uses

@enduml
114 changes: 114 additions & 0 deletions actor-model/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).

The MIT License
Copyright © 2014-2022 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>

<artifactId>actor-model</artifactId>
<name>Actor Model</name>

<!-- Force unified JUnit version to avoid classpath mismatches -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add maven-assembly-plugin so that we can execute the jar from the command line


<build>
<plugins>
<!-- Assembly plugin for creating fat JARs -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.iluwatar.actormodel.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>

</plugin>
</plugins>
</build>

</project>
Loading
Loading