Active object explained
The active object design pattern decouples method execution from method invocation for objects that each reside in their own thread of control.[1] The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.[2]
The pattern consists of six elements:[3]
- A proxy, which provides an interface towards clients with publicly accessible methods.
- An interface which defines the method request on an active object.
- A list of pending requests from clients.
- A scheduler, which decides which request to execute next.
- The implementation of the active object method.
- A callback or variable for the client to receive the result.
Example
Java
An example of active object pattern in Java.[4]
Firstly we can see a standard class that provides two methods that set a double to be a certain value. This class does NOT conform to the active object pattern.
class MyClass
The class is dangerous in a multithreading scenario because both methods can be called simultaneously, so the value of val (which is not atomic—it's updated in multiple steps) could be undefined—a classic race condition. You can, of course, use synchronization to solve this problem, which in this trivial case is easy. But once the class becomes realistically complex, synchronization can become very difficult. [5]
To rewrite this class as an active object, you could do the following:
class MyActiveObject
Java 8 (alternative)
Another example of active object pattern in Java instead implemented in Java 8 providing a shorter solution.
public class MyClass
See also
External links
Notes and References
- Book: Douglas C. Schmidt . Michael Stal. Hans Rohnert. Frank Buschmann . 2000 . Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects . John Wiley & Sons . 0-471-60695-2. Douglas C. Schmidt.
- Bass, L., Clements, P., Kazman, R. Software Architecture in Practice. Addison Wesley, 2003
- Web site: Active Object . R. Greg . Lavender . Schmidt, Douglas C. . 2007-02-02 . https://web.archive.org/web/20120722180050/http://www.cs.wustl.edu/%7Eschmidt/PDF/Act-Obj.pdf . 2012-07-22 . dead .
- Web site: Java Active Objects - A Proposal . Allen . Holub . 2014-06-16 . https://web.archive.org/web/20130622122643/http://pragprog.com/magazines/2013-05/java-active-objects . 2013-06-22 . dead .
- Web site: Java Active Objects - A Proposal . Allen . Holub . 2014-06-16 . https://web.archive.org/web/20130622122643/http://pragprog.com/magazines/2013-05/java-active-objects . 2013-06-22 . dead .