|
| 1 | +--- |
| 2 | +shortTitle: Active Object |
| 3 | +category: Concurrency |
| 4 | +language: de |
| 5 | +tag: |
| 6 | + - Asynchronous |
| 7 | + - Decoupling |
| 8 | + - Messaging |
| 9 | + - Synchronization |
| 10 | + - Thread management |
| 11 | +--- |
| 12 | + |
| 13 | +## Zweck |
| 14 | + |
| 15 | +Active Object bietet eine zuverlässige Methode zur Behandlung asynchroner Prozesse, mit der reaktionsfähige Anwendungen |
| 16 | +und effizientes Thread-Management gesichert werden. |
| 17 | +Dies wird dadurch erreicht, dass die einzelnen Aufgaben in Objekte gekapselt werden, die in eigenen Threads |
| 18 | +mit eigener Nachrichtenwarteschlange aktiv sind. Durch diese Trennung bleibt der Hauptthread |
| 19 | +reaktionsfähig und Probleme wie direkte Threadmanipulation oder gemeinsamer Zugriff auf Zustände werden vermieden. |
| 20 | + |
| 21 | +## Detaillierte Erklärung |
| 22 | + |
| 23 | +Reales Beispiel |
| 24 | + |
| 25 | +> Stellen Sie sich ein gut besuchtes Restaurant vor, in dem die Gäste Bestellungen bei den |
| 26 | +> Kellner aufgeben. Die Kellner gehen nicht selbst in die Küche, um die Essen selbst zuzubereiten, |
| 27 | +> sondern sie schreiben die Bestellungen auf Zettel und geben diese dem Küchenmanager. |
| 28 | +> Der Manager organisiert eine Gruppe von Köchen, die die verschiedenen Mahlzeiten parallel zubereiten. |
| 29 | +> Wenn ein Koch frei ist, nimmt er eine Bestellung aus der Warteschlange, bereitet das Essen zu |
| 30 | +> und benachrichtigt den Kellner, sobald es fertig zum Servieren ist. |
| 31 | +> |
| 32 | +> In dieser Analogie stehen die Kellner für die Client-Threads, |
| 33 | +> der Küchenmanager für den Thread-Scheduler, und die Köche für die Methodenausführung |
| 34 | +> in verschiedenen Threads. |
| 35 | +> Die Organisation ermöglicht es, dass die Kellner immer weiter Bestellungen annehmen können, |
| 36 | +> ohne durch die Essenszubereitung aufgehalten zu werden; so wie das Active-Object-Pattern |
| 37 | +> den Methodenaufruf von der Ausführung trennt, um die Effizienz zu verbessern. |
| 38 | +
|
| 39 | +In einfachen Worten |
| 40 | + |
| 41 | +> Das Active-Object-Pattern trennt Methodenausführung und Methodenaufruf, |
| 42 | +> um Parallelitätsgrad und Reaktionsfähigkeit in Multithread-Anwendungen zu verbessern. |
| 43 | +
|
| 44 | +Wikipedia sagt |
| 45 | + |
| 46 | +> Das Design-Pattern Active Object entkoppelt die Methodenausführung vom Methodenaufruf |
| 47 | +> für Objekte, die in ihrem jeweils eigenen Thread arbeiten.[1] |
| 48 | +> Ziel ist, Parallelität dadurch zu ermöglichen, dass Methoden asynchron aufgerufen werden und ein |
| 49 | +> Scheduler die Anfragen organisiert. |
| 50 | +> |
| 51 | +> Das Pattern besteht aus sechs Elementen. |
| 52 | +> |
| 53 | +> * Ein Proxy stellt für Clients ein Interface mit öffentlich zugänglichen Methoden zur Verfügung. |
| 54 | +> * Ein weiteres Interface definiert die Anfragen an ein aktives Objekt. |
| 55 | +> * Eine Liste offener Client-Anfragen. |
| 56 | +> * Ein Scheduler entscheidet, welche Anfrage als nächstes ausgeführt wird. |
| 57 | +> * Die Implementation der Methoden. |
| 58 | +> * Eine Callback-Variable zur Rückmeldung des Ergebnisses. |
| 59 | +
|
| 60 | +Ablaufdiagramm |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +## Programmatic Example of Active Object in Java |
| 66 | + |
| 67 | +This section explains how the Active Object design pattern works in Java, highlighting its use in asynchronous task management and concurrency control. |
| 68 | + |
| 69 | +The Orcs are known for their wildness and untameable soul. It seems like they have their own thread of control based on previous behavior. To implement a creature that has its own thread of control mechanism and expose its API only and not the execution itself, we can use the Active Object pattern. |
| 70 | + |
| 71 | +```java |
| 72 | +public abstract class ActiveCreature { |
| 73 | + private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName()); |
| 74 | + |
| 75 | + private BlockingQueue<Runnable> requests; |
| 76 | + |
| 77 | + private String name; |
| 78 | + |
| 79 | + private Thread thread; |
| 80 | + |
| 81 | + public ActiveCreature(String name) { |
| 82 | + this.name = name; |
| 83 | + this.requests = new LinkedBlockingQueue<Runnable>(); |
| 84 | + thread = new Thread(new Runnable() { |
| 85 | + @Override |
| 86 | + public void run() { |
| 87 | + while (true) { |
| 88 | + try { |
| 89 | + requests.take().run(); |
| 90 | + } catch (InterruptedException e) { |
| 91 | + logger.error(e.getMessage()); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + ); |
| 97 | + thread.start(); |
| 98 | + } |
| 99 | + |
| 100 | + public void eat() throws InterruptedException { |
| 101 | + requests.put(new Runnable() { |
| 102 | + @Override |
| 103 | + public void run() { |
| 104 | + logger.info("{} is eating!", name()); |
| 105 | + logger.info("{} has finished eating!", name()); |
| 106 | + } |
| 107 | + } |
| 108 | + ); |
| 109 | + } |
| 110 | + |
| 111 | + public void roam() throws InterruptedException { |
| 112 | + requests.put(new Runnable() { |
| 113 | + @Override |
| 114 | + public void run() { |
| 115 | + logger.info("{} has started to roam the wastelands.", name()); |
| 116 | + } |
| 117 | + } |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + public String name() { |
| 122 | + return this.name; |
| 123 | + } |
| 124 | +} |
| 125 | +``` |
| 126 | + |
| 127 | +We can see that any class that will extend the `ActiveCreature` class will have its own thread of control to invoke and execute methods. |
| 128 | + |
| 129 | +For example, the `Orc` class: |
| 130 | + |
| 131 | +```java |
| 132 | +public class Orc extends ActiveCreature { |
| 133 | + |
| 134 | + public Orc(String name) { |
| 135 | + super(name); |
| 136 | + } |
| 137 | +} |
| 138 | +``` |
| 139 | + |
| 140 | +Now, we can create multiple creatures such as orcs, tell them to eat and roam, and they will execute it on their own thread of control: |
| 141 | + |
| 142 | +```java |
| 143 | +public class App implements Runnable { |
| 144 | + |
| 145 | + private static final Logger logger = LoggerFactory.getLogger(App.class.getName()); |
| 146 | + |
| 147 | + private static final int NUM_CREATURES = 3; |
| 148 | + |
| 149 | + public static void main(String[] args) { |
| 150 | + var app = new App(); |
| 151 | + app.run(); |
| 152 | + } |
| 153 | + |
| 154 | + @Override |
| 155 | + public void run() { |
| 156 | + List<ActiveCreature> creatures = new ArrayList<>(); |
| 157 | + try { |
| 158 | + for (int i = 0; i < NUM_CREATURES; i++) { |
| 159 | + creatures.add(new Orc(Orc.class.getSimpleName() + i)); |
| 160 | + creatures.get(i).eat(); |
| 161 | + creatures.get(i).roam(); |
| 162 | + } |
| 163 | + Thread.sleep(1000); |
| 164 | + } catch (InterruptedException e) { |
| 165 | + logger.error(e.getMessage()); |
| 166 | + Thread.currentThread().interrupt(); |
| 167 | + } finally { |
| 168 | + for (int i = 0; i < NUM_CREATURES; i++) { |
| 169 | + creatures.get(i).kill(0); |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | +} |
| 174 | +``` |
| 175 | + |
| 176 | +Program output: |
| 177 | + |
| 178 | +``` |
| 179 | +09:00:02.501 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 is eating! |
| 180 | +09:00:02.501 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 is eating! |
| 181 | +09:00:02.501 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 is eating! |
| 182 | +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has finished eating! |
| 183 | +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has finished eating! |
| 184 | +09:00:02.504 [Thread-0] INFO com.iluwatar.activeobject.ActiveCreature -- Orc0 has started to roam in the wastelands. |
| 185 | +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has finished eating! |
| 186 | +09:00:02.504 [Thread-1] INFO com.iluwatar.activeobject.ActiveCreature -- Orc1 has started to roam in the wastelands. |
| 187 | +09:00:02.504 [Thread-2] INFO com.iluwatar.activeobject.ActiveCreature -- Orc2 has started to roam in the wastelands. |
| 188 | +``` |
| 189 | + |
| 190 | +## When to Use the Active Object Pattern in Java |
| 191 | + |
| 192 | +Use the Active Object pattern in Java when: |
| 193 | + |
| 194 | +* when you need to handle asynchronous tasks without blocking the main thread, ensuring better performance and responsiveness. |
| 195 | +* When you need to interact with external resources asynchronously. |
| 196 | +* When you want to improve the responsiveness of your application. |
| 197 | +* When you need to manage concurrent tasks in a modular and maintainable way. |
| 198 | + |
| 199 | +## Active Object Pattern Java Tutorials |
| 200 | + |
| 201 | +* [Android and Java Concurrency: The Active Object Pattern(Douglas Schmidt)](https://www.youtube.com/watch?v=Cd8t2u5Qmvc) |
| 202 | + |
| 203 | +## Real-World Applications of Active Object Pattern in Java |
| 204 | + |
| 205 | +* Real-time trading systems where transaction requests are handled asynchronously. |
| 206 | +* GUIs where long-running tasks are executed in the background without freezing the user interface. |
| 207 | +* Game programming to handle concurrent updates to game state or AI computations. |
| 208 | + |
| 209 | +## Benefits and Trade-offs of Active Object Pattern |
| 210 | + |
| 211 | +Discover the benefits and trade-offs of using the Active Object pattern in Java, including improved thread safety and potential overhead concerns. |
| 212 | + |
| 213 | +Benefits: |
| 214 | + |
| 215 | +* Improves responsiveness of the main thread. |
| 216 | +* Encapsulates concurrency concerns within objects. |
| 217 | +* Promotes better code organization and maintainability. |
| 218 | +* Provides thread safety and avoids shared state access problems. |
| 219 | + |
| 220 | +Trade-offs: |
| 221 | + |
| 222 | +* Introduces additional overhead due to message passing and thread management. |
| 223 | +* May not be suitable for all types of concurrency problems. |
| 224 | + |
| 225 | +## Related Java Design Patterns |
| 226 | + |
| 227 | +* [Command](https://java-design-patterns.com/patterns/command/): Encapsulates a request as an object, similarly to how the Active Object pattern encapsulates method calls. |
| 228 | +* [Promise](https://java-design-patterns.com/patterns/promise/): Provides a means to retrieve the result of an asynchronous method call, often used in conjunction with Active Object. |
| 229 | +* [Proxy](https://java-design-patterns.com/patterns/proxy/): The Active Object pattern can use a proxy to handle method invocations asynchronously. |
| 230 | + |
| 231 | +## References and Credits |
| 232 | + |
| 233 | +* [Design Patterns: Elements of Reusable Object Software](https://amzn.to/3HYqrBE) |
| 234 | +* [Concurrent Programming in Java: Design Principles and Patterns](https://amzn.to/498SRVq) |
| 235 | +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) |
| 236 | +* [Learning Concurrent Programming in Scala](https://amzn.to/3UE07nV) |
| 237 | +* [Pattern Languages of Program Design 3](https://amzn.to/3OI1j61) |
| 238 | +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) |
0 commit comments