Thursday, October 31, 2024

Handling long operations in observer chains

If you have lengthy observer notification chains where observers notify other observers, making the trigger order unpredictable, and these chains include time-consuming operations like updating a map drawing, you can use the following approach to only update the drawing when the last observer in the chain is reached:
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicInteger;
public class DrawLast extends Observable implements Observer {
// Global static AtomicInteger to ensure thread safety
public static final AtomicInteger activeDrawingObserverCount = new AtomicInteger(0);
@Override
public void update(Observable o, Object arg) {
// Increment count safely
DrawLast.activeDrawingObserverCount.incrementAndGet();
try {
// Do observer-specific operations
System.out.println("Observer " + this + " is updating...");
// Notify other observers, assuming each follows the same pattern in this update()
setChanged();
notifyObservers();
} finally {
// Decrement count safely in a finally block
int remainingObservers = DrawLast.activeDrawingObserverCount.decrementAndGet();
if (remainingObservers == 0) {
draw(); // Call draw only when all observers are done
}
}
}
private void draw() {
System.out.println("Drawing now that all observers are done.");
}
public static void main(String[] args) {
DrawLast observer1 = new DrawLast();
DrawLast observer2 = new DrawLast();
DrawLast observer3 = new DrawLast(); // Last observer in the chain
// Set up observers to observe each other in a chain
observer1.addObserver(observer2);
observer2.addObserver(observer3);
// Start the chain by notifying observer1
observer1.setChanged();
observer1.notifyObservers();
}
}
view raw DrawLast.java hosted with ❤ by GitHub

No comments:

Post a Comment