|By Steven Schwell||
|October 1, 1997 12:00 AM EDT||
The Observer Design Pattern is among the most useful for object-oriented software design. The JDK itself makes heavy use of a variant of this pattern in the 1.1 AWT event delegation model. The JDK also provides a reusable embodiment of the pattern in the form of the java.util.Observer interface and the java.util.Observable class. If you've done much serious Java programming you've more than likely had occasion to use these classes.
The idea of the pattern is to model a one-to-many dependency without tightly coupling the observed object with its many observers. When the observed object changes in some interesting way it can automatically notify all of its observers without knowing them directly. For more on this pattern, see Qusay Mahmoud's article, "Implementing Design Patterns in Java" (JDJ, Vol. 2, Iss. 5), or the Design Patterns book.
Unfortunately, a number of weaknesses have been identified in the JDK's Observer/Observable classes. Peter Coad and Mark Mayfield discuss some of these weaknesses in their excellent book, Java Design. These weaknesses significantly limit the reusability and power of the classes, which is a shame since powerful reusability is a big part of what object-oriented design is all about.
Most of the weaknesses are due to the fact that java.util.Observable is a class rather than an interface; or rather, that it is a class without a corresponding interface. This implies that the only way to reuse Observable is to subclass it. You can't take an existing class and tack on the role of Observable by having it implement an Observable interface because there is no Observable interface.
What if you have a class that is already in a class hierarchy and also needs to play the role of an Observable? Since Java doesn't support multiple inheritance, you're out of luck. That class cannot extend from Observable because it is already extending from some other class.
It also means that you are stuck with the one and only implementation of Observable in java.util.Observable. For a variety of reasons, you may want to use an alternate implementation - e.g., to do the notification in a separate thread or in a particular order. You may even want to vary the implementation of Observable at runtime. There is no Observable interface for your alternate implementations to implement. You cannot reuse Observable by composition so you cannot vary the composed Observable implementation at runtime.
The designers of the Observable class broke two general principles of object-oriented design with Java. The first principle is to design with interfaces rather than classes. Whenever possible, avoid committing yourself to a particular implementation of an interface. The second principle is to favor reuse by composition over reuse by inheritance unless a class hierarchy is clearly indicated. By omitting an Observable interface and making some of its methods protected, the designers made it impossible to reuse Observable by composition.
A minor weakness in Observable is the necessity to call setChanged() before notifySubscribers(). The intention there seems to be to eliminate needless notifications in cases where there is no interesting change to the Observable. There may be situations in which this two-stage notification is appropriate, but it isn't the simplest case and programmers shouldn't be forced to use this implementation in all situations. Also, setChanged() is protected, further reinforcing the necessity to reuse the class only by inheritance.
Now let's look at the Observer interface. The weakness here is its tight coupling with the Observable class. The first parameter to the update() method is unnecessarily typed as an Observable. If it were typed more generally as a simple Object, the Observer interface would be more reusable. It then could be used with any Observable implementation or even in any situation, completely unrelated to Observer/Observable, which called for a void method with two Object parameters.
Despite all these weaknesses, I was initially reluctant to ignore the JDK classes in favor of the homegrown replacements suggested by Coad and Mayfield. After all, the JDK classes are already locally available to every VM and they do serve their purpose nicely for the majority of cases. On the other hand, designing for maximal reuse is crucial to the success of any object-oriented design. A little forethought early in the game can lead to great savings down the road. Luckily, when I started a new project some months ago, I decided to take the plunge and start using the improved classes.
More recently I began designing a number of distributed three-tier Java apps using Remote Method Invocation (RMI). It turns out that the Observer pattern has great application to remote applications. A remote object that lives on the server often needs to be observed by multiple objects living on multiple clients. When the remote object changes, all clients need to find out in order to, for example, update the user's view.
The JDK's Observer/Observable classes are of no use here. They do not extend from java.rmi.Remote and their method signatures do not allow for the possible throwing of RemoteException. Both of these are required of any Remote interface for RMI. So the JDK's Observable/Observer classes can never be implemented as an RMI remote interface of a RemoteObject.
The solution that I've seen in articles and books is to write a separate set of classes for Remote Observable/Observer. This always seemed wrong to me. Why should I have to write, support and use two disjoint sets of classes to do basically the same thing albeit in different situations? What if I have a class that needs to notify both local and remote Observers? You mean it has to implement both versions of Observable?!
Having already severed my dependence on the JDK's Observable classes, I was able to painlessly enhance my classes to support Remote Method Invocation. The same classes can now be used for local Observers as well as remote Observers or even for a mixture of remote and local Observers.
The interfaces are shown in Listing 1. In order to avoid confusion with the JDK classes, I use the synonymous terminology of Publisher/Subscriber rather than Observable/Observer.
Notice that the Publisher and Subscriber interfaces extend from java.rmi.Remote and all their methods may throw RemoteException. This is so that these interfaces may be implemented by remote classes for use with RMI. These additions do not preclude these classes from being used in a strictly local situation without RMI. In fact, the same Publisher could be used to publish to a mixture of local and remote Subscribers.
A simple basic implementation of Publisher is presented in Listing 2. This Publisher can be used for both local and remote Subscribers.
The notifySubscribers() method deserves some elaboration. The call to the Subscribers' update() method is in a try/catch clause to deal with possibly thrown RemoteExceptions. Two particular RemoteExceptions, ConnectException and NoSuchObjectException, are considered serious enough to consider the Subscriber to be dead. Subscribers that are considered dead are removed from the list of Subscribers for this Publisher. Other RemoteExceptions may be indications of transient failures that could correct themselves. This is the type of fuzzy logic you need to apply in networked situations where errors are unpredictable and non-deterministic.
The dead Subscribers are not removed from the list of Subscribers until after the list is enumerated. At first glance you might ask, why not remove the dead Observers right away, within the catch clauses? This is because of a quirk in java.util.Vector that makes it unsafe to manipulate a Vector while it is being enumerated. This quirk (bug?) is a discussion for another time, but a few words about the workaround I chose are warranted here.
As I discover Subscribers that are to be considered dead, I accumulate them in a Vector. Only after enumeration of all Subscribers do I go through the Vector of dead Subscribers and actually remove them. Another workaround that I could have used is to clone the Vector of Subscribers before enumerating it. Then I could operate on the original Vector while enumerating the clone. I chose the workaround I did because it has little overhead for the more usual case when no RemoteException is thrown. Even the deadSubs Vector is not allocated until and unless it is needed. This technique is known as lazy instantiation.
The preferred way to reuse BasicPublisher is by composition. Any class that needs to play the role of a Publisher should implement the Publisher interface and include a reference to an instance of BasicPublisher to do the work of a Publisher. Listing 3 is a rough outline of this.
Class XX is free to extend from some other class if it needs to and it can publish changes to subscribers, whether local or remote, by calling pub.notifySubscribers(). You can also reuse BasicPublisher by subclassing it, but this is not the preferred way. It eliminates the need to delegate the Publisher interface but it reduces the extendibility of the class because the class can no longer be a subclass of any other class.
To use these classes with RMI, the classes that implement Publisher and Subscriber must be remote objects. Without going into too much detail on RMI, let me just point out that any class can be made remote in two simple steps. First, add the following to its constructor:
UnicastRemoteObject.exportObject(this); and recompile. Second, run the rmic post compiler on the class. That's it. Your class is now remote. Remote publishers can now publish changes to local subscribers in the same VM or to remote subscribers in other VMs.
In summary, these two interfaces and class constitute a far more powerful and reusable embodiment of the Observer design pattern than the JDK's Observer/Observable. They can even be used for remote Observers with RMI. This is just the sort of weapon in your object-oriented arsenal that makes Java programming such a joy.
Gamma, E., Johnson, R. and Vlissides, J., "Design Patterns: Elements of Object-Oriented Architecture", Addison-Wesley, Reading, MA, 1995.
Coad , P. and Mayfield, M., "Java Design: Building Better Apps and Applets", Yourdon Press, Upper Saddle River, NJ, 1997.
Electric power utilities face relentless pressure on their financial performance, and reducing distribution grid losses is one of the last untapped opportunities to meet their business goals. Combining IoT-enabled sensors and cloud-based data analytics, utilities now are able to find, quantify and reduce losses faster – and with a smaller IT footprint. Solutions exist using Internet-enabled sensors deployed temporarily at strategic locations within the distribution grid to measure actual line loads.
Oct. 10, 2015 02:00 PM EDT Reads: 153
The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, will explore the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.
Oct. 10, 2015 01:45 PM EDT Reads: 147
SYS-CON Events announced today that IBM Cloud Data Services has been named “Bronze Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. IBM Cloud Data Services offers a portfolio of integrated, best-of-breed cloud data services for developers focused on mobile computing and analytics use cases.
Oct. 10, 2015 01:00 PM EDT Reads: 756
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
Oct. 10, 2015 01:00 PM EDT Reads: 269
Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi's VP Business Development and Engineering, will explore the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context w...
Oct. 10, 2015 01:00 PM EDT Reads: 164
As a company adopts a DevOps approach to software development, what are key things that both the Dev and Ops side of the business must keep in mind to ensure effective continuous delivery? In his session at DevOps Summit, Mark Hydar, Head of DevOps, Ericsson TV Platforms, will share best practices and provide helpful tips for Ops teams to adopt an open line of communication with the development side of the house to ensure success between the two sides.
Oct. 10, 2015 11:00 AM EDT Reads: 643
There will be 20 billion IoT devices connected to the Internet soon. What if we could control these devices with our voice, mind, or gestures? What if we could teach these devices how to talk to each other? What if these devices could learn how to interact with us (and each other) to make our lives better? What if Jarvis was real? How can I gain these super powers? In his session at 17th Cloud Expo, Chris Matthieu, co-founder and CTO of Octoblu, will show you!
Oct. 10, 2015 11:00 AM EDT Reads: 137
Developing software for the Internet of Things (IoT) comes with its own set of challenges. Security, privacy, and unified standards are a few key issues. In addition, each IoT product is comprised of at least three separate application components: the software embedded in the device, the backend big-data service, and the mobile application for the end user's controls. Each component is developed by a different team, using different technologies and practices, and deployed to a different stack/target - this makes the integration of these separate pipelines and the coordination of software upd...
Oct. 10, 2015 11:00 AM EDT Reads: 336
Mobile messaging has been a popular communication channel for more than 20 years. Finnish engineer Matti Makkonen invented the idea for SMS (Short Message Service) in 1984, making his vision a reality on December 3, 1992 by sending the first message ("Happy Christmas") from a PC to a cell phone. Since then, the technology has evolved immensely, from both a technology standpoint, and in our everyday uses for it. Originally used for person-to-person (P2P) communication, i.e., Sally sends a text message to Betty – mobile messaging now offers tremendous value to businesses for customer and empl...
Oct. 10, 2015 10:15 AM EDT Reads: 338
SYS-CON Events announced today that Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, will keynote at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA.
Oct. 10, 2015 10:00 AM EDT Reads: 152
The IoT market is on track to hit $7.1 trillion in 2020. The reality is that only a handful of companies are ready for this massive demand. There are a lot of barriers, paint points, traps, and hidden roadblocks. How can we deal with these issues and challenges? The paradigm has changed. Old-style ad-hoc trial-and-error ways will certainly lead you to the dead end. What is mandatory is an overarching and adaptive approach to effectively handle the rapid changes and exponential growth.
Oct. 10, 2015 10:00 AM EDT Reads: 258
The IoT is upon us, but today’s databases, built on 30-year-old math, require multiple platforms to create a single solution. Data demands of the IoT require Big Data systems that can handle ingest, transactions and analytics concurrently adapting to varied situations as they occur, with speed at scale. In his session at @ThingsExpo, Chad Jones, chief strategy officer at Deep Information Sciences, will look differently at IoT data so enterprises can fully leverage their IoT potential. He’ll share tips on how to speed up business initiatives, harness Big Data and remain one step ahead by apply...
Oct. 10, 2015 09:00 AM EDT Reads: 653
WebRTC converts the entire network into a ubiquitous communications cloud thereby connecting anytime, anywhere through any point. In his session at WebRTC Summit,, Mark Castleman, EIR at Bell Labs and Head of Future X Labs, will discuss how the transformational nature of communications is achieved through the democratizing force of WebRTC. WebRTC is doing for voice what HTML did for web content.
Oct. 10, 2015 09:00 AM EDT Reads: 1,448
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Oct. 10, 2015 07:00 AM EDT Reads: 5,960
WebRTC has had a real tough three or four years, and so have those working with it. Only a few short years ago, the development world were excited about WebRTC and proclaiming how awesome it was. You might have played with the technology a couple of years ago, only to find the extra infrastructure requirements were painful to implement and poorly documented. This probably left a bitter taste in your mouth, especially when things went wrong.
Oct. 10, 2015 06:00 AM EDT Reads: 828
The broad selection of hardware, the rapid evolution of operating systems and the time-to-market for mobile apps has been so rapid that new challenges for developers and engineers arise every day. Security, testing, hosting, and other metrics have to be considered through the process. In his session at Big Data Expo, Walter Maguire, Chief Field Technologist, HP Big Data Group, at Hewlett-Packard, will discuss the challenges faced by developers and a composite Big Data applications builder, focusing on how to help solve the problems that developers are continuously battling.
Oct. 10, 2015 04:00 AM EDT Reads: 523
Nowadays, a large number of sensors and devices are connected to the network. Leading-edge IoT technologies integrate various types of sensor data to create a new value for several business decision scenarios. The transparent cloud is a model of a new IoT emergence service platform. Many service providers store and access various types of sensor data in order to create and find out new business values by integrating such data.
Oct. 10, 2015 04:00 AM EDT Reads: 611
There are so many tools and techniques for data analytics that even for a data scientist the choices, possible systems, and even the types of data can be daunting. In his session at @ThingsExpo, Chris Harrold, Global CTO for Big Data Solutions for EMC Corporation, will show how to perform a simple, but meaningful analysis of social sentiment data using freely available tools that take only minutes to download and install. Participants will get the download information, scripts, and complete end-to-end walkthrough of the analysis from start to finish. Participants will also be given the pract...
Oct. 10, 2015 03:00 AM EDT Reads: 343
WebRTC: together these advances have created a perfect storm of technologies that are disrupting and transforming classic communications models and ecosystems. In his session at WebRTC Summit, Cary Bran, VP of Innovation and New Ventures at Plantronics and PLT Labs, will provide an overview of this technological shift, including associated business and consumer communications impacts, and opportunities it may enable, complement or entirely transform.
Oct. 10, 2015 02:15 AM EDT Reads: 773
SYS-CON Events announced today that Dyn, the worldwide leader in Internet Performance, will exhibit at SYS-CON's 17th International Cloud Expo®, which will take place on November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Dyn is a cloud-based Internet Performance company. Dyn helps companies monitor, control, and optimize online infrastructure for an exceptional end-user experience. Through a world-class network and unrivaled, objective intelligence into Internet conditions, Dyn ensures traffic gets delivered faster, safer, and more reliably than ever.
Oct. 10, 2015 02:00 AM EDT Reads: 665