-
-
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
base: master
Are you sure you want to change the base?
Changes from 7 commits
f543057
3ee44ea
11abf48
dd1dcdd
9ad06e6
c6685e9
c0ecf29
afd64e0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# Actor Model | ||
|
||
## Intent | ||
|
||
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. | ||
|
||
## Explanation | ||
|
||
### Real-world Example | ||
|
||
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. | ||
|
||
### Problem | ||
|
||
Managing concurrent behavior in a safe and scalable way is difficult, especially with shared memory and race conditions. | ||
|
||
### Solution | ||
|
||
Encapsulate state and behavior within individual actors that communicate through asynchronous messages. | ||
|
||
## Class Diagram | ||
|
||
 | ||
|
||
## Participants | ||
|
||
- **Actor**: Base class that defines a mailbox and handles incoming messages sequentially. | ||
- **Message**: Represents communication between actors. | ||
- **ActorSystem**: Creates and manages actors. | ||
- **PrinterActor**: Sample actor that prints incoming messages. | ||
|
||
## Applicability | ||
|
||
Use the Actor Model pattern when: | ||
|
||
- You need a simple and safe way to handle concurrency. | ||
- You want to avoid thread synchronization issues like race conditions and deadlocks. | ||
- You want each object to process messages independently. | ||
|
||
## Example | ||
|
||
```java | ||
ActorSystem system = new ActorSystem(); | ||
Actor printer = system.actorOf(new PrinterActor()); | ||
|
||
printer.send(new Message("Hello Actor!", null)); | ||
printer.send(new Message("Another message", null)); | ||
|
||
Thread.sleep(1000); | ||
|
||
((PrinterActor) printer).stop(); | ||
system.shutdown(); |
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 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
<?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> | ||
|
||
<dependencies> | ||
<!-- JUnit 5 Jupiter API --> | ||
<dependency> | ||
<groupId>org.junit.jupiter</groupId> | ||
<artifactId>junit-jupiter-api</artifactId> | ||
<version>5.10.0</version> | ||
<scope>test</scope> | ||
</dependency> | ||
|
||
<!-- JUnit 5 Jupiter Engine --> | ||
<dependency> | ||
<groupId>org.junit.jupiter</groupId> | ||
<artifactId>junit-jupiter-engine</artifactId> | ||
<version>5.10.0</version> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use the version from the parent pom.xml |
||
<scope>test</scope> | ||
</dependency> | ||
</dependencies> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
||
|
||
</project> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
/* | ||
* 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. | ||
*/ | ||
package com.iluwatar.actormodel; | ||
|
||
import java.util.concurrent.BlockingQueue; | ||
import java.util.concurrent.LinkedBlockingQueue; | ||
import lombok.Getter; | ||
import lombok.Setter; | ||
|
||
public abstract class Actor implements Runnable { | ||
|
||
@Setter @Getter private String actorId; | ||
private final BlockingQueue<Message> mailbox = new LinkedBlockingQueue<>(); | ||
private volatile boolean active = | ||
true; // always read from main memory and written back to main memory, | ||
|
||
// rather than being cached in a thread's local memory. To make it consistent to all Actors | ||
|
||
public void send(Message message) { | ||
mailbox.add(message); // Add message to queue | ||
} | ||
|
||
public void stop() { | ||
active = false; // Stop the actor loop | ||
} | ||
|
||
@Override | ||
public void run() { | ||
while (active) { | ||
try { | ||
Message message = mailbox.take(); // Wait for a message | ||
onReceive(message); // Process it | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
} | ||
} | ||
} | ||
|
||
// Child classes must define what to do with a message | ||
protected abstract void onReceive(Message message); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* | ||
* 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. | ||
*/ | ||
package com.iluwatar.actormodel; | ||
|
||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
public class ActorSystem { | ||
private final ExecutorService executor = Executors.newCachedThreadPool(); | ||
private final ConcurrentHashMap<String, Actor> actorRegister = new ConcurrentHashMap<>(); | ||
private final AtomicInteger idCounter = new AtomicInteger(0); | ||
|
||
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 | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
/* | ||
* 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. | ||
*/ | ||
package com.iluwatar.actormodel; | ||
|
||
public class App { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here, above the |
||
public static void main(String[] args) throws InterruptedException { | ||
ActorSystem system = new ActorSystem(); | ||
Actor srijan = new ExampleActor(system); | ||
system.startActor(srijan); | ||
Actor ansh = new ExampleActor2(system); | ||
system.startActor(ansh); | ||
ansh.send(new Message("Hello Srijan", srijan.getActorId())); | ||
srijan.send(new Message("Hello ansh!", srijan.getActorId())); | ||
|
||
Thread.sleep(1000); // Give time for messages to process | ||
|
||
srijan.stop(); // Stop the actor gracefully | ||
ansh.stop(); | ||
system.shutdown(); // Stop the actor system | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/* | ||
* 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. | ||
*/ | ||
package com.iluwatar.actormodel; | ||
|
||
import java.util.logging.Logger; | ||
|
||
public class ExampleActor extends Actor { | ||
private final ActorSystem actorSystem; | ||
|
||
public ExampleActor(ActorSystem actorSystem) { | ||
this.actorSystem = actorSystem; | ||
} | ||
|
||
Logger logger = Logger.getLogger(getClass().getName()); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use Lombok's @slf4j annotation for logging |
||
|
||
@Override | ||
protected void onReceive(Message message) { | ||
logger.info("[" + getActorId() + "]" + "Received : " + message.getContent()); | ||
|
||
Actor sender = actorSystem.getActorById(message.getSenderId()); // sender actor id | ||
if (sender != null && !message.getSenderId().equals(getActorId())) { | ||
sender.send(new Message("I got your message ", getActorId())); | ||
} | ||
} | ||
} |
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.
Check out the
README.md
template here: https://github.com/iluwatar/java-design-patterns/wiki/21.-New-Pattern-Template