Active object

Last updated

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]

Contents

The pattern consists of six elements: [3]

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.

classMyClass{privatedoubleval=0.0;voiddoSomething(){val=1.0;}voiddoSomethingElse(){val=2.0;}}

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:

classMyActiveObject{privatedoubleval=0.0;privateBlockingQueue<Runnable>dispatchQueue=newLinkedBlockingQueue<Runnable>();publicMyActiveObject(){newThread(newRunnable(){@Overridepublicvoidrun(){try{while(true){dispatchQueue.take().run();}}catch(InterruptedExceptione){// okay, just terminate the dispatcher}}}).start();}voiddoSomething()throwsInterruptedException{dispatchQueue.put(newRunnable(){@Overridepublicvoidrun(){val=1.0;}});}voiddoSomethingElse()throwsInterruptedException{dispatchQueue.put(newRunnable(){@Overridepublicvoidrun(){val=2.0;}});}}

Java 8 (alternative)

Another example of active object pattern in Java instead implemented in Java 8 providing a shorter solution.

publicclassMyClass{privatedoubleval;// container for tasks// decides which request to execute next // asyncMode=true means our worker thread processes its local task queue in the FIFO order // only single thread may modify internal stateprivatefinalForkJoinPoolfj=newForkJoinPool(1,ForkJoinPool.defaultForkJoinWorkerThreadFactory,null,true);// implementation of active object methodpublicvoiddoSomething()throwsInterruptedException{fj.execute(()->{val=1.0;});}// implementation of active object methodpublicvoiddoSomethingElse()throwsInterruptedException{fj.execute(()->{val=2.0;});}}

See also

Related Research Articles

A visitor pattern is a software design pattern that separates the algorithm from the object structure. Because of this separation new operations can be added to existing object structures without modifying the structures. It is one way to follow the open/closed principle in object-oriented programming and software engineering.

<span class="mw-page-title-main">Jakarta Servlet</span> Jakarta EE programming language class

A Jakarta Servlet, formerly Java Servlet is a Java software component that extends the capabilities of a server. Although servlets can respond to many types of requests, they most commonly implement web containers for hosting web applications on web servers and thus qualify as a server-side servlet web API. Such web servlets are the Java counterpart to other dynamic web content technologies such as PHP and ASP.NET.

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

In concurrent programming, guarded suspension is a software design pattern for managing operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed. The guarded suspension pattern is typically applied to method calls in object-oriented programs, and involves suspending the method call, and the calling thread, until the precondition is satisfied.

<span class="mw-page-title-main">Swing (Java)</span> Java-based GUI toolkit

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part of (runtime) polymorphism in object-oriented programming (OOP). They allow for the execution of target functions that were not precisely identified at compile time.

In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to call back (execute) the callback function as part of its job. This execution may be immediate as in a synchronous callback, or it might happen at a later point in time as in an asynchronous callback. They are also called blocking and non-blocking.

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

<span class="mw-page-title-main">Method overriding</span> Language feature in object-oriented programming

Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition to providing data-driven algorithm-determined parameters across virtual network interfaces, it also allows for a specific type of polymorphism (subtyping). The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. This helps in preventing problems associated with differential relay analytics which would otherwise rely on a framework in which method overriding might be obviated. Some languages allow a programmer to prevent a method from being overridden.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. It is an example of the generic concept of event-driven programming, that is popular in many other contexts than Java, for example, web browsers, or web servers.

SwingWorker is a utility class developed by Sun Microsystems for the Swing library of the Java programming language. SwingWorker enables proper use of the event dispatching thread. As of Java 6, SwingWorker is included in the JRE.

Java Pathfinder (JPF) is a system to verify executable Java bytecode programs. JPF was developed at the NASA Ames Research Center and open sourced in 2005. The acronym JPF is not to be confused with the unrelated Java Plugin Framework project.

The Java programming language and the Java virtual machine (JVM) is designed to support concurrent programming. All execution takes place in the context of threads. Objects and resources can be accessed by many separate threads. Each thread has its own path of execution, but can potentially access any object in the program. The programmer must ensure read and write access to objects is properly coordinated between threads. Thread synchronization ensures that objects are modified by only one thread at a time and prevents threads from accessing partially updated objects during modification by another thread. The Java language has built-in constructs to support this coordination.

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior, was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

The front controller software design pattern is listed in several pattern catalogs and is related to the design of web applications. It is "a controller that handles all requests for a website," which is a useful structure for web application developers to achieve flexibility and reuse without code redundancy.

Join-patterns provides a way to write concurrent, parallel and distributed computer programs by message passing. Compared to the use of threads and locks, this is a high level programming model using communication constructs model to abstract the complexity of concurrent environment and to allow scalability. Its focus is on the execution of a chord between messages atomically consumed from a group of channels.

Intercepting Filter is a JavaEE pattern which creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code. The filters intercept incoming requests and outgoing responses, allowing preprocessing and post-processing, and these filters can be added or removed unobtrusively without changing existing code. This pattern applies reusable processing transparently before and after the actual request execution by the front and page controllers.

References

  1. 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. ISBN   0-471-60695-2.
  2. Bass, L., Clements, P., Kazman, R. Software Architecture in Practice. Addison Wesley, 2003
  3. Lavender, R. Greg; Schmidt, Douglas C. "Active Object" (PDF). Archived from the original (PDF) on 2012-07-22. Retrieved 2007-02-02.
  4. Holub, Allen. "Java Active Objects - A Proposal". Archived from the original on 2013-06-22. Retrieved 2014-06-16.
  5. Holub, Allen. "Java Active Objects - A Proposal". Archived from the original on 2013-06-22. Retrieved 2014-06-16.