Home > Articles > Programming > Java

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.

Figure 4-42

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.

Figure 4-43

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.

Figure 4-44

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.



Footnote

  1. As of this writing, a similar class is scheduled to be supported in an upcoming SDK release.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020