4.5 Active Objects
In the task-based frameworks illustrated throughout most of this chapter, threads are used to propel conceptually active messages sent among conceptually passive objects. However, it can be productive to approach some design problems from the opposite perspective active objects sending each other passive messages.
To illustrate, consider an active object that conforms to the WaterTank description in Chapter 1:
pseudoclass ActiveWaterTank extends Thread { // Pseudocode // ... public void run() { for (;;) { accept message; if (message is of form addWater(float amount)) { if (currentVolume >= capacity) { if (overflow != null) { send overflow.addWater(amount); accept response; if (response is of form OverflowException) reply response; else ... else ... else ... } else if (message is of form removeWater(float amount)) { ... } } } }
Pseudocode is used here because there is no built-in syntax for passing messages from one active object to another, only for direct invocation among passive objects. However, as discussed in 4.1.1, similar issues may be encountered even when using passive objects. Any of the solutions described there apply equally well here: adopting message formats of various kinds, transported across streams, channels, event queues, pipes, sockets, and so on. In fact, as shown in the WebService example leading off this chapter, it is easy to add task-based constructions to designs otherwise based on active objects. Conversely, most task-based designs discussed in this chapter work equally well when some objects are active rather than passive.
Further, the use of Runnables as messages leads to a boring but universal (at least in some senses) form of active object: a minor variant of a common worker thread design that also conforms to the initial abstract characterization of active objects as interpreters in 1.2.4:
class ActiveRunnableExecutor extends Thread { Channel me = ... // used for all incoming messages public void run() { try { for (;;) { ((Runnable)(me.take())).run(); } } catch (InterruptedException ie) {} // die } }
Of course, such classes are not very useful unless they also include internal methods that manufacture Runnables to execute and/or send to other active objects. It is possible, but unnatural, to write entire programs in this fashion.
However, many components in reactive systems can be usefully construed as active objects that operate under more constrained rules and message-passing disciplines. This includes especially those objects that interact with other computers or devices, often the main externally visible objects in a program.
In distributed frameworks such as CORBA and RMI, externally visible active objects are themselves ascribed interfaces listing the messages that they accept. Internally, they usually have a more uniform structure than does ActiveWaterTank. Typically, they contain a main run loop that repeatedly accepts external requests, dispatches to internal passive objects providing the corresponding service, and then constructs reply messages that are sent back to clients. (The internal passive objects are the ones explicitly programmed when using CORBA and RMI. The active objects, sometimes known as skeletons, are usually generated automatically by tools.)
It is very possible to take an active, actor-style approach to the design of other components as well. One reason for designing entire systems from this point of view is to take advantage of well-developed theory and design techniques associated with particular sets of rules surrounding active entities and their messages. The remainder of this section gives a brief overview of the most well-known and influential such framework, CSP.
4.5.1 CSP
C.A.R. Hoare's theory of Communicating Sequential Processes (CSP) provides both a formal approach to concurrency and an associated set of design techniques. As discussed in the Further Readings in 4.5.2, there are a number of closely related approaches, but CSP has had the largest impact on concurrent design and programming. CSP has served as the basis of programming languages (including occam), was influential in the design of others (including Ada), and can be supported in the Java programming language through the use of library classes.
The following account illustrates the JCSP package developed by Peter Welch and colleagues. The package is available via links from the online supplement. This section provides only a brief synopsis. Interested readers will want to obtain copies of the package, its documentation, and related texts.
4.5.1.1 Processes and channels
A CSP process can be construed as a special kind of actor-style object, in which:
-
Processes have no method interface and no externally invocable methods. Because there are no invocable methods, it is impossible for methods to be invoked by different threads. Thus there is no need for explicit locking.
-
Processes communicate only by reading and writing data across channels.
-
Processes have no identity, and so cannot be explicitly referenced. However, channels serve as analogs of references (see 1.2.4), allowing communication with whichever process is at the other end of a channel.
-
Processes need not spin forever in a loop accepting messages (although many do). They may read and write messages on various channels as desired.
A CSP channel can be construed as a special kind of Channel, in which:
-
All channels are synchronous (see 3.4.1.4), and so contain no internal buffering. (However, you can construct processes that perform buffering.)
-
Channels support only read ("?") and write ("!") operations carrying data values. The operations behave in the same way as take and put.
-
The most fundamental channels are one-to-one. They may be connected only to a single pair of processes, a writer and a reader. Multiple-reader and multiple-writer channels may also be defined.
4.5.1.2 Composition
Much of the elegance of CSP stems from its simple and analytically tractable composition rules. The "S" in CSP stands for Sequential, so basic processes perform serial computations on internal data (for example adding numbers, conditional tests, assignment, looping). Higher-level processes are built by composition; for a channel c, variable x, and processes P and Q:
c?x -> P |
Reading from c enables P |
c!x -> P |
Writing to c enables P |
P ; Q |
P followed by Q |
P || Q |
P and Q in parallel |
P [ ] Q |
P or Q (but not both) |
The choice operator P [ ] Q requires that P and Q both be communication-enabled processes (of form d?y -> R or d!y -> R). The choice of which process runs depends on which communication is ready: Nothing happens until one or both communications are ready. If one is (or becomes) ready, that branch is taken. If both are (or become) ready, either choice may be taken (nondeterministically).
4.5.1.3 JCSP
The JCSP package supports CSP-based design in a straightforward way. It consists of an execution framework that efficiently supports CSP constructs represented via interfaces, classes, and methods, including:
-
Interfaces ChannelInput (supporting read), ChannelOutput (supporting write) and Channel (supporting both) operate on Object arguments, but special versions for int arguments are also provided. The principal implementation class is One2OneChannel that supports use only by a single reader and a single writer. But various multiway channels are also provided.
-
Interface CSProcess describes processes supporting only method run. Implementation classes Parallel and Sequence (and others) have constructors that accept arrays of other CSProcess objects and create composites.
-
The choice operator [ ] is supported via the Alternative class. Its constructor accepts arrays with elements of type Guard. Alternative supports a select method that returns an index denoting which of them can (and then must) be chosen. A fairSelect method works in the same way but provides additional fairness guarantees over the course of multiple selects, it will choose fairly among all ready alternatives rather than always selecting one of them. The only usages of Alternative demonstrated below use guard type AltingChannelInput, which is implemented by One2OneChannel.
-
Additional utilities include CSProcess implementations such as Timer (which does delayed writes and can also be used for time-outs in Alternative), Generate (which generates number sequences), Skip (which does nothing at all one of the CSP primitives), and classes that permit interaction and display via AWT.
4.5.1.4 Dining philosophers
As a classic demonstration, consider the famous Dining Philosophers problem. A table holds five forks (arranged as pictured) and a bowl of spaghetti. It seats five philosophers, each of whom eat for a while, then think for a while, then eat, and so on. Each philosopher requires two forks the ones on the left and right to eat (no one knows why; it is just part of the story) but releases them when thinking.
The main problem to be solved here is that, without some kind of coordination, the philosophers could starve when they pick up their left forks and then block forever trying to pick up their right forks which are being held by other philosophers.
There are many paths to a solution (and yet more paths to non-solution). We'll demonstrate one described by Hoare that adds a requirement (enforced by a Butler) that at any given time, at most four philosophers are allowed to be seated. This requirement suffices to ensure that at all times at least one philosopher can eat if there are only four philosophers, at least one of them can get both forks. This solution does not by itself ensure that all five philosophers eventually eat. But this guarantee can be obtained via use of Alternative.fairSelect in the Butler class to ensure fair processing of seating messages.
We'll use a simple, pure CSP style where all channels are one-to-one and messages have no content (using null for messages). This puts a stronger focus on the synchronization and process construction issues. The system is composed of a College with five Philosophers, five Forks, and one Butler (standing in the bowl of spaghetti!), connected using One2OneChannels.
Since everything must be either a process or a channel, forks must be processes. A Fork continuously loops waiting for a message from one of its users (either its left-hand or right-hand philosopher). When it gets a message from one indicating a fork pick-up, it waits for another indicating a fork put-down. (While it might be more tasteful to indicate pick-ups versus put-downs via different kinds of messages or message contents, this protocol using null messages suffices.)
In JCSP, this can be written as:
class Fork implements CSProcess { private final AltingChannelInput[ ] fromPhil; Fork(AltingChannelInput l, AltingChannelInput r) { fromPhil = new AltingChannelInput[ ] { l, r }; } public void run() { Alternative alt = new Alternative(fromPhil); for (;;) { int i = alt.select(); // await message from either fromPhil[i].read(); // pick up fromPhil[i].read(); // put down } } }
The Butler process makes sure that at most N-1 (i.e., four here) philosophers are seated at any given time. It does this by enabling both enter and exit messages if there are enough seats, but only exit messages otherwise. Because Alternative operates on arrays of alternatives, this requires a bit of manipulation to set up. (Some other utilities in JCSP could be used to simplify this.) The exit channels are placed before the enter channels in the chans array so that the proper channel will be read no matter which Alternative is used. The fairSelect is employed here to ensure that the same four philosophers are not always chosen if a fifth is also trying to enter.
class Butler implements CSProcess { private final AltingChannelInput[ ] enters; private final AltingChannelInput[ ] exits; Butler(AltingChannelInput[ ] e, AltingChannelInput[ ] x) { enters = e; exits = x; } public void run() { int seats = enters.length; int nseated = 0; // set up arrays for select AltingChannelInput[ ] chans = new AltingChannelInput[2*seats]; for (int i = 0; i < seats; ++i) { chans[i] = exits[i]; chans[seats + i] = enters[i]; } Alternative either = new Alternative(chans); Alternative exit = new Alternative(exits); for (;;) { // if max number are seated, only allow exits Alternative alt = (nseated < seats-1)? either : exit; int i = alt.fairSelect(); chans[i].read(); // if i is in first half of array, it is an exit message if (i < seats) --nseated; else ++nseated; } } }
The Philosopher processes run forever in a loop, alternating between thinking and eating. Before eating, philosophers must first enter their seats, then get both forks. After eating, they do the opposite. The eat and think methods are just no-ops here, but could be fleshed out to (for example) help animate a demonstration version by reporting status to JCSP channels and processes that interface into AWT.
class Philosopher implements CSProcess { private final ChannelOutput leftFork; private final ChannelOutput rightFork; private final ChannelOutput enter; private final ChannelOutput exit; Philosopher(ChannelOutput l, ChannelOutput r, ChannelOutput e, ChannelOutput x) { leftFork = l; rightFork = r; enter = e; exit = x; } public void run() { for (;;) { think(); enter.write(null); // get seat leftFork.write(null); // pick up left rightFork.write(null); // pick up right eat(); leftFork.write(null); // put down left rightFork.write(null); // put down right exit.write(null); // leave seat } } private void eat() {} private void think() {} }
Finally, we can create a College class to represent the parallel composition of the Forks, Philosophers, and Butler. The channels are constructed using a JCSP convenience function create that creates arrays of channels. The Parallel constructor accepts an array of CSProcess, which is first loaded with all of the participants.
class College implements CSProcess { final static int N = 5; private final CSProcess action; College() { One2OneChannel[ ] lefts = One2OneChannel.create(N); One2OneChannel[ ] rights = One2OneChannel.create(N); One2OneChannel[ ] enters = One2OneChannel.create(N); One2OneChannel[ ] exits = One2OneChannel.create(N); Butler butler = new Butler(enters, exits); Philosopher[ ] phils = new Philosopher[N]; for (int i = 0; i < N; ++i) phils[i] = new Philosopher(lefts[i], rights[i], enters[i], exits[i]); Fork[] forks = new Fork[N]; for (int i = 0; i < N; ++i) forks[i] = new Fork(rights[(i + 1) % N], lefts[i]); action = new Parallel( new CSProcess[ ] { butler, new Parallel(phils), new Parallel(forks) }); } public void run() { action.run(); } public static void main(String[ ] args) { new College().run(); } }
4.5.2 Further Readings
CSP has proven to be a successful approach to the design and analysis of systems that can be usefully expressed as bounded sets of identityless, interfaceless processes communicating via synchronous channels. CSP was introduced in:
Hoare, C. A. R. Communicating Sequential Processes, Prentice Hall, 1985.
An updated account appears in:
Roscoe, A. William. The Theory and Practice of Concurrency, Prentice Hall, 1997.
Several of the texts listed in Chapter 1 (including the book by Burns and Welling in 1.2.5.4) discuss CSP in the course of describing constructs in occam and Ada.
Other related formalisms, design techniques, languages, and frameworks have adopted different base assumptions that adhere more closely to the characteristics of other concurrent systems and/or to different styles of analysis. These include Milner's CCS and pi-calculus, and Berry's Esterel. See:
Milner, Robin. Communication and Concurrency, Prentice Hall, 1989.
Berry, Gerard. "The Foundations of Esterel", in Gordon Plotkin, Colin Stirling, and Mads Tofte (eds.), Proof, Language and Interaction, MIT Press, 1998.
As package support becomes available for these and related approaches to concurrent system design, they become attractive alternatives to the direct use of thread-based constructs in the development of systems that are best viewed conceptually as collections of active objects. For example, Triveni is an approach based in part on Esterel, and is described in:
Colby, Christopher, Lalita Jategaonkar Jagadeesan, Radha Jagadeesan, Konstantin L ufer, and Carlos Puchol. "Objects and Concurrency in Triveni: A Telecommunication Case Study in Java", USENIX Conference on Object-Oriented Technologies and Systems (COOTS), 1998.
Triveni is supported by a Java programming language package (see the online supplement). Among its main differences from CSP is that active objects in Triveni communicate by issuing events. Triveni also includes computation and composition rules surrounding the interruption and suspension of activities upon reception of events, which adds to expressiveness especially in real-time design contexts.