Showing posts with label Observer and Observable. Show all posts
Showing posts with label Observer and Observable. Show all posts

Sunday, 17 March 2019

How to remove the Observer from the Observable in Java? | Observer and O...

Want to Master Java Design Patterns?

Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

Subscribe on YouTube

Managing Observers in Java's Observable Class

In event-driven architectures and the Observer Design Pattern, registering observers is only half the picture. To avoid memory leaks, unwanted event handling, and redundant notifications, applications must have clean mechanisms to unregister or unsubscribe observers when they are no longer needed.

Java's built-in java.util.Observable provides two primary methods to detach listeners:

  • deleteObserver(Observer o): Removes a specific observer from the internal observer list.
  • deleteObservers(): Clears and unregisters all active observers in a single operation.

How deleteObserver and deleteObservers Work

Consider an e-commerce price alert model where customer observers (such as PeterObserver and JohnObserver) listen for price changes on a product like NokiaMobilePriceObservable:

  • Initial State: Both observers are registered using addObserver(). Calling countObservers() returns 2. When the price changes, both receive notifications.
  • Removing a Single Observer: Calling deleteObserver(peterObserver) unregisters Peter. The count drops to 1, and subsequent price modifications will notify only John.
  • Removing All Observers: Calling deleteObservers() cleans up all remaining registrations, dropping the active count to 0. No further notifications are dispatched.

Why Observer Deregistration Matters

  • Prevents Memory Leaks: Known as the "lapsed listener" problem, keeping lingering references inside subjects prevents garbage collection of unused observer objects.
  • Optimizes Performance: Eliminates processing overhead by ensuring notifications are dispatched only to components actively listening.
  • Dynamic Lifecycle Control: Gives clients complete runtime authority over when to subscribe or unsubscribe from subject notifications.

Related Observer Pattern Tutorials to Watch Next

Example of Observer and Observable in Java? | Observer and Observable

Want to Master Java Design Patterns?

Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

Subscribe on YouTube

Real-Time Example: Mobile Price Tracking Alert System

The Observer Design Pattern is widely applied in real-time notification systems, such as e-commerce price alerts, stock market updates, and live score trackers. In Java, this pattern can be implemented directly using the built-in java.util.Observer interface and java.util.Observable class.

In this scenario, a mobile phone's price changes dynamically, and multiple registered customers (observers) need to be instantly informed whenever an update occurs.

Core Participants in the Application

  • NokiaMobilePriceObservable (Subject/Observable): Extends Observable. It maintains the product price attribute and dispatches updates using setChanged() and notifyObservers().
  • JohnObserver & PeterObserver (Concrete Observers): Implement the Observer interface and override the update(Observable o, Object arg) method to react to price revisions.
  • ObservableDemo (Driver Class): Registers the observers with the observable and simulates changing the product price to trigger notifications.

Step-by-Step Implementation Flow

  1. Define Observers: Create classes like JohnObserver and PeterObserver implementing java.util.Observer to receive and print notifications when update() is invoked.
  2. Create the Observable: Subclass java.util.Observable to create NokiaMobilePriceObservable. When setPrice() is called, flag the change with setChanged() and notify listeners via notifyObservers().
  3. Subscribe & Trigger: In the client code, instantiate the mobile observable with an initial price, attach both observers using addObserver(), and update the price to observe automatic event delivery.

Why Use Observer and Observable?

  • Loose Coupling: The observable subject does not need to know the internal implementation details of John or Peter; it only interacts via the standard Observer interface.
  • Broadcasting Capabilities: Supports one-to-many communication, allowing any number of interested observers to subscribe or unsubscribe at runtime.
  • Clean Event Architecture: Eliminates continuous polling by letting the subject automatically push data updates as soon as state changes happen.

Related Observer Pattern Tutorials to Watch Next

What is the Observer and Observable in Java? | Observer and Observable

Want to Master Java Design Patterns?

Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

Subscribe on YouTube

What Are Observer and Observable in Java?

In software design, keeping dependent objects synchronized when a core data model changes is a common requirement. In Java, this is directly supported via the built-in classes in the java.util package:

  • java.util.Observable (Class): Represents the subject or model being observed. It maintains an internal list of observers and notifies them whenever its state changes.
  • java.util.Observer (Interface): Implemented by any class that wants to be informed of state changes occurring in an Observable object.

This mechanism forms the backbone of the classic Model-View paradigm and the Observer Design Pattern, decoupling state management from event listeners.

How the Notification Workflow Works

  1. Observer Registration: Observers implement the Observer interface and its update(Observable o, Object arg) method. They register with the observable instance using addObserver(Observer o).
  2. State Modification: When internal state changes (e.g., product price updates), the observable invokes setChanged() to flag that a state modification occurred.
  3. Automatic Broadcasting: The observable calls notifyObservers(), which loops through all registered observers and triggers each observer's update() method automatically.

Key Architectural Benefits

  • Loose Coupling: The subject only interacts with listeners through the generic Observer interface without caring about their concrete classes.
  • One-to-Many Communication: Easily supports multiple independent listeners receiving simultaneous updates.
  • Event-Driven Design: Replaces continuous polling with immediate, event-triggered updates.

Related Observer Pattern Tutorials to Watch Next

Tutorials