-
-
Notifications
You must be signed in to change notification settings - Fork 26.9k
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
ssrijan-007-sys
wants to merge
8
commits into
iluwatar:master
Choose a base branch
from
ssrijan-007-sys:actor-model
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f543057
feat: Implement Actor Model pattern #3232
ssrijan-007-sys 3ee44ea
feat: Implement Actor Model pattern #3232
ssrijan-007-sys 11abf48
feat: update Actor Model implementation with multi-actor logic #3251
ssrijan-007-sys dd1dcdd
Merge branch 'iluwatar:master' into actor-model
ssrijan-007-sys 9ad06e6
feat: update Actor Model implementation with multi-actor logic and lo…
ssrijan-007-sys c6685e9
test: add unit test for actor model #3251
ssrijan-007-sys c0ecf29
test: add test for App.java to increase coverage
ssrijan-007-sys afd64e0
docs: add complete README for Actor Model pattern also implemented ch…
ssrijan-007-sys File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
 | ||
|
||
--- | ||
|
||
## 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) | ||
|
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
|
||
<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> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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