This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |