- Concurrent Object-Oriented Programming
- 2 Objects and Concurrency
- 3 Design Forces
- 4 Before/After Patterns
1.4 Before/After Patterns
Many concurrent designs are best described as patterns. A pattern encapsulates a successful and common design form, usually an object structure (also known as a micro-architecture) consisting of one or more interfaces, classes, and/or objects that obey certain static and dynamic constraints and relationships. Patterns are an ideal vehicle for characterizing designs and techniques that need not be implemented in exactly the same way across different contexts, and thus cannot be usefully encapsulated as reusable components. Reusable components and frameworks can play a central role in concurrent software development. But much of concurrent OO programming entails the reuse, adaptation, and extension of recurring design forms and practices rather than of particular classes.
Unlike those in the pioneering Design Patterns book by Gamma, Helm, Johnson, and Vlissides (see Further Readings in 1.4.5), the patterns here are embedded within chapters discussing sets of related contexts and software design principles that generate the main forces and constraints resolved in the patterns. Many of these patterns are minor extensions or variants of other common OO layering and composition patterns. This section reviews some that are relied on heavily in subsequent chapters. Others are briefly described upon first encounter.
1.4.1 Layering
Layering policy control over mechanism is a common structuring principle in systems of all sorts. Many OO layering and composition techniques rely on sandwiching some method call or body of code between a given before-action and an after-action. All forms of before/after control arrange that a given ground method, say method, is intercepted so as always to execute in the sequence:
before(); method(); after();
Or, to ensure that after-actions are performed even if the ground methods encounter exceptions:
before(); try { method(); } finally { after(); }
Most examples in this book of course revolve around concurrency control. For example, a synchronized method acquires a lock before executing the code inside the method, and releases the lock after the method otherwise completes. But the basic ideas of before/after patterns can be illustrated in conjunction with another useful practice in OO programming, self-checking code: The fields of any object should preserve all invariants whenever the object is not engaged in a public method (see 1.3.1). Invariants should be maintained even if these methods throw any of their declared exceptions, unless these exceptions denote corruption or program failure (as may be true for RuntimeExceptions and Errors).
Conformance to computable invariants can be tested dynamically by creating classes that check them both on entry to and on exit from every public method. Similar techniques apply to preconditions and postconditions, but for simplicity, we'll illustrate only with invariants.
As an example, suppose we'd like to create water tank classes that contain a self-check on the invariant that the volume is always between zero and the capacity. To do this, we can define a checkVolumeInvariant method and use it as both the before and after operation. We can first define an exception to throw if the invariant fails:
class AssertionError extends java.lang.Error { public AssertionError() { super(); } public AssertionError(String message) { super(message); } }
It can be disruptive to insert these checks manually inside each method. Instead, one of three before/after design patterns can be used to separate the checks from the ground methods: adapter classes, subclass-based designs, and method adapter classes.
In all cases, the best way to set this up is to define an interface describing the basic functionality. Interfaces are almost always necessary when you need to give yourself enough room to vary implementations. Conversely, the lack of existing interfaces limits options when retrospectively applying before/after patterns.
Here is an interface describing a minor variant of the water tank class discussed in 1.2.4. Before/after techniques may be applied to check invariants around the transferWater operation.
interface Tank { float getCapacity(); float getVolume(); void transferWater(float amount) throws OverflowException, UnderflowException; }
1.4.2 Adapters
When standardized interfaces are defined after designing one or more concrete classes, these classes often do not quite implement the desired interface. For example, the names of their methods might be slightly different from those defined in the interface. If you cannot modify these concrete classes to fix such problems, you can still obtain the desired effect by building an Adapter class that translates away the incompatibilities.
Say you have a Performer class that supports method perform and meets all the qualifications of being usable as a Runnable except for the name mismatch. You can build an Adapter so it can be used in a thread by some other class:
class AdaptedPerformer implements Runnable { private final Performer adaptee; public AdaptedPerformer(Performer p) { adaptee = p; } public void run() { adaptee.perform(); } }
This is only one of many common contexts for building Adapters, which also form the basis of several related patterns presented in the Design Patterns book. A Proxy is an Adapter with the same interface as its delegate. A Composite maintains a collection of delegates, all supporting the same interface.
In this delegation-based style of composition, the publicly accessible host class forwards all methods to one or more delegates and relays back replies, perhaps doing some light translation (name changes, parameter coercion, result filtering, etc.) surrounding the delegate calls.
Adapters can be used to provide before/after control merely by wrapping the delegated call within the control actions. For example, assuming that we have an implementation class, say TankImpl, we can write the following AdaptedTank class. This class can be used instead of the original in some application by replacing all occurrences of:
new TankImpl(...)
with:
new AdaptedTank(new TankImpl(...)). class AdaptedTank implements Tank { protected final Tank delegate; public AdaptedTank(Tank t) { delegate = t; } public float getCapacity() { return delegate.getCapacity(); } public float getVolume() { return delegate.getVolume(); } protected void checkVolumeInvariant() throws AssertionError { float v = getVolume(); float c = getCapacity(); if ( !(v >= 0.0 && v <= c) ) throw new AssertionError(); } public synchronized void transferWater(float amount) throws OverflowException, UnderflowException { checkVolumeInvariant(); // before-check try { delegate.transferWater(amount); } // The re-throws will be postponed until after-check // in the finally clause catch (OverflowException ex) { throw ex; } catch (UnderflowException ex) { throw ex; } finally { checkVolumeInvariant(); // after-check } } }
1.4.3 Subclassing
In the normal case, when the intercepted before/after versions of methods have the same names and usages as base versions, subclassing can be a simpler alternative to the use of Adapters. Subclass versions of methods can interpose checks around calls to their super versions. For example:
class SubclassedTank extends TankImpl { protected void checkVolumeInvariant() throws AssertionError { // ... identical to AdaptedTank version ... } public synchronized void transferWater(float amount) throws OverflowException, UnderflowException { // identical to AdaptedTank version except for inner call: // ... try { super.transferWater(amount); } // ... } }
Some choices between subclassing and Adapters are just a matter of style. Others reflect differences between delegation and inheritance.
Adapters permit manipulations that escape subclassing rules. For example, you cannot override a public method as private in a subclass in order to disable access, but you can simply fail to relay the method in an Adapter. Various forms of delegation can even be used as a substitute of sorts for subclassing by having each "sub" class (Adapter) hold a reference to an instance of its "super" class (Adaptee), forwarding it all "inherited" operations. Such Adapters often have exactly the same interfaces as their delegates, in which case they are considered to be simple kinds of Proxies. Delegation can also be more flexible than subclassing, since "sub" objects can even change their "supers" (by reassigning the delegate reference) dynamically.
Delegation can also be used to obtain the effects of multiple code inheritance. For example, if a class must implement two unrelated interfaces, say Tank and java.awt.event.ActionListener, and there are two available superclasses providing the needed functionality, then one of these may be subclassed and the other delegated.
However, delegation is less powerful than subclassing in some other respects. For example, self-calls in "superclasses" are not automatically bound to the versions of methods that have been "overridden" in delegation-based "subclasses". Adapter designs can also run into snags revolving around the fact that the Adaptee and Adapter objects are different objects. For example, object reference equality tests must be performed more carefully since a test to see if you have the Adaptee version of an object fails if you have the Adapter version, and vice versa.
Most of these problems can be avoided via the extreme measure of declaring all methods in Adaptee classes to take an "apparent self" argument referring to the Adapter, and always using it instead of this, even for self-calls and identity checks (for example by overriding Object.equals). Some people reserve the term delegation for objects and classes written in this style rather than the forwarding techniques that are almost always used to implement simple Adapters.
1.4.3.1 Template methods
When you are pretty sure that you are going to rely on before/after control in a set of related classes, you can create an abstract class that automates the control sequence via an application of the Template Method pattern (which has nothing to do with C++ generic types).
An abstract class supporting template methods sets up a framework facilitating construction of subclasses that may override the ground-level actions, the before/after methods, or both:
-
Basic ground-level action code is defined in non-public methods. (By convention, we name the non-public version of any method method as doMethod.) Somewhat less flexibly, these methods need not be declared non-public if they are instead designed to be overridden in subclasses.
-
Before and after operations are also defined as non-public methods.
-
Public methods invoke the ground methods between the before and after methods.
Applying this to the Tank example leads to:
abstract class AbstractTank implements Tank { protected void checkVolumeInvariant() throws AssertionError { // ... identical to AdaptedTank version ... } protected abstract void doTransferWater(float amount) throws OverflowException, UnderflowException; public synchronized void transferWater(float amount) throws OverflowException, UnderflowException { // identical to AdaptedTank version except for inner call: // ... try { doTransferWater(amount); } // ... } } class ConcreteTank extends AbstractTank { protected final float capacity; protected float volume; // ... public float getVolume() { return volume; } public float getCapacity() { return capacity; } protected void doTransferWater(float amount) throws OverflowException, UnderflowException { // ... implementation code ... } }
1.4.4 Method Adapters
The most flexible, but sometimes most awkward approach to before/after control is to define a class whose entire purpose is to invoke a particular method on a particular object. In the Command Object pattern and its many variants, instances of such classes can then be passed around, manipulated, and ultimately executed (here, between before/after operations).
Because of static typing rules, there must be a different kind of adapter class for each kind of method being wrapped. To avoid proliferation of all these types, most applications restrict attention to only one or a small set of generic interfaces, each defining a single method. For example, the Thread class and most other execution frameworks accept only instances of interface Runnable in order to invoke their argumentless, resultless, exceptionless run methods. Similarly, in 4.3.3.1, we define and use interface Callable containing only a method call that accepts one Object argument, returns an Object, and may throw any Exception.
In more focused applications, you can define any suitable single-method interface, instantiate an implementation almost always via an anonymous inner class and then pass it around for later execution. This technique is used extensively in the java.awt and javax.swing packages, which define interfaces and abstract classes associated with different kinds of event-handling methods. (In some other languages, function pointers and closures are defined and used to achieve some of these effects.)
We can apply a version of before/after layering based on method adapters here by first defining a TankOp interface:
interface TankOp { void op() throws OverflowException, UnderflowException; }
In the following sample code, uncharacteristically, all uses of method adapters are local to the TankWithMethodAdapter class. Also, in this tiny example, there is only one wrappable method. However, the same scaffolding could be used for any other Tank methods defined in this class or its subclasses. Method adapters are much more common in applications where instances must be registered and/or passed around among multiple objects before being executed, which justifies the extra setup costs and programming obligations.
class TankWithMethodAdapter { // ... protected void checkVolumeInvariant() throws AssertionError { // ... identical to AdaptedTank version ... } protected void runWithinBeforeAfterChecks(TankOp cmd) throws OverflowException, UnderflowException { // identical to AdaptedTank.transferWater // except for inner call: // ... try { cmd.op(); } // ... } protected void doTransferWater(float amount) throws OverflowException, UnderflowException { // ... implementation code ... } public synchronized void transferWater(final float amount) throws OverflowException, UnderflowException { runWithinBeforeAfterChecks(new TankOp() { public void op() throws OverflowException, UnderflowException { doTransferWater(amount); } }); } }
Some applications of method adapters can be partially automated by using reflection facilities. A generic constructor can probe a class for a particular java.lang.reflect.Method, set up arguments for it, invoke it, and transfer back results. This comes at the price of weaker static guarantees, greater overhead, and the need to deal with the many exceptions that can arise. So this is generally only worthwhile when dealing with unknown dynamically loaded code.
More extreme and exotic reflective interception techniques are available if you escape the confines of the language. For example, it is possible to create and apply tools that splice bytecodes representing before and after actions into compiled class representations or do so upon class-loading.
1.4.5 Further Readings
There are many useful design patterns besides those that are particular to concurrent programming, and surely many others relating to concurrency that are not included in this book. Other books presenting patterns and pattern-related aspects of software design include:
Buschmann, Frank, Regine Meunier, Hans Rohnert, Peter Sommerlad, and Michael Stal. Pattern-Oriented Software Architecture: A System of Patterns, Wiley, 1996.
Coplien, James. Advanced C++: Programming Styles and Idioms, Addison-Wesley, 1992.
Fowler, Martin. Analysis Patterns, Addison-Wesley, 1997
Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns, Addison-Wesley, 1994. (The "Gang of Four" book.)
Rising, Linda. The Patterns Handbook, Cambridge University Press, 1998.
Shaw, Mary, and David Garlan. Software Architecture, Prentice Hall, 1996.
(Various editors) Pattern Languages of Program Design, Addison-Wesley. This series incorporates patterns presented at the annual Pattern Languages of Programming (PLoP) conference.
The OO language Self is among the few that directly support a pure delegation-based style of programming without requiring explicit message forwarding. See:
Ungar, David. "The Self Papers", Lisp and Symbolic Computation, 1991.
Reflective before/after techniques are often seen in Lisp, Scheme and CLOS (the Common Lisp Object System). See, for example:
Abelson, Harold, and Gerald Sussman. Structure and Interpretation of Computer Programs, MIT Press, 1996.
Kiczales, Gregor, Jim des Rivieres, and Daniel Bobrow. The Art of the Metaobject Protocol, MIT Press, 1993.
Additional layered synchronization design patterns are discussed in:
Rito Silva, Ant nio, Jo o Pereira and Jos Alves Marques. "Object Synchronizer", in Neil Harrison, Brian Foote and Hans Rohnert (eds.), Pattern Languages of Program Design, Volume 4, Addison-Wesley, 1999.
A compositional approach to layering concurrency control is described in:
Holmes, David. Synchronisation Rings: Composable Synchronisation for Concurrent Object Oriented Systems, PhD Thesis, Macquarie University, 1999.
Composition of collections of before/after methods that deal with different aspects of functionality (for example, mixing synchronization control with persistence control) may require more elaborate frameworks than discussed here. One approach is to construct a metaclass framework that partially automates the interception and wrapping of methods by class objects. For an extensive analysis and discussion of the resulting composition techniques, see:
Forman, Ira, and Scott Danforth. Putting Metaclasses to Work, Addison-Wesley, 1999.
Aspect-oriented programming replaces layered before/after techniques with tools that weave together code dealing with different aspects of control. Reports on the language AspectJ include some examples from this book expressed in an aspect-oriented fashion. See:
Kiczales, Gregor, John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Videira Lopes, Jean-Marc Loingtier, and John Irwin. "Aspect-Oriented Programming", Proceedings of the European Conference on Object-Oriented Programming (ECOOP), 1997.
Several tools are available for partially automating invariant tests. See, for example:
Beck, Kent, and Erich Gamma. "Test Infected: Programmers Love Writing Tests", The Java Report, July 1998.