Bird
Raised Fist0

Review the following thread-safe observer pattern snippet. Identify the line that causes unsubscribed observers to still receive event notifications.

medium🐞 Bug Q7 of Q15
OOP & Design Patterns - Observer Pattern - Event System, Publish-Subscribe
Review the following thread-safe observer pattern snippet. Identify the line that causes unsubscribed observers to still receive event notifications.

import threading

class Subject:
    def __init__(self):
        self.lock = threading.Lock()
        self.observers = {}

    def subscribe(self, observer, event):
        with self.lock:
            self.observers.setdefault(event, set()).add(observer)

    def unsubscribe(self, observer, event):
        with self.lock:
            self.observers[event].remove(observer)

    def notify(self, event, message):
        with self.lock:
            observers = self.observers.get(event, set())
        for obs in observers:
            obs.update(event, message)
ALine: observers = self.observers.get(event, set()) in notify()
BLine: self.observers[event].remove(observer) in unsubscribe()
CLine: self.observers.setdefault(event, set()).add(observer) in subscribe()
DLine: for obs in observers: obs.update(event, message) in notify()
Step-by-Step Solution
Solution:
  1. Step 1: Understand unsubscribe

    Unsubscribe removes observer from the set under lock.
  2. Step 2: Analyze notify

    Notify copies the set reference without making a snapshot copy, so if unsubscribe modifies the set concurrently, iteration may include removed observers.
  3. Step 3: Identify bug

    Line getting observers directly without copying causes unsubscribed observers to still receive notifications.
  4. Final Answer:

    Line: observers = self.observers.get(event, set()) in notify() -> Option A
  5. Quick Check:

    Notify must snapshot observers to avoid race conditions [OK]
Quick Trick: Notify must copy observers to avoid race conditions [OK]
Common Mistakes:
MISTAKES
  • Assuming remove() always prevents notifications immediately
  • Not realizing iteration over mutable set causes race issues
Trap Explanation:
PITFALL
  • Directly iterating over mutable observer sets causes stale notifications.
Interviewer Note:
CONTEXT
  • Tests knowledge of thread safety and snapshotting in observer notification.
Master "Observer Pattern - Event System, Publish-Subscribe" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes