Ensuring proper encapsulation
medium 40 minPrivate fields are the start, not the end.
Watch lesson4:46
Two threads
Correct methods, called in between each other.
The point: an invariant over two fields, or a check followed by an act, must be one step. If the caller has to combine calls, the class has leaked its locking duty.
Three safe methods, one broken program
Check outside, act inside
Python
import threadingclass Account: def __init__(self, cents): self.__lock = threading.Lock() # private: nobody else can hold it self._cents = cents self._entries = [cents] def withdraw(self, cents): # the check and the act are one step if cents <= 0: raise ValueError("amount must be positive") with self.__lock: if cents > self._cents: return False self._cents -= cents self._entries.append(-cents) return True def statement(self): # two fields that belong together with self.__lock: return self._cents, tuple(self._entries)acc = Account(1000)won = []def work(): for _ in range(50): if acc.withdraw(7): won.append(7)ts = [threading.Thread(target=work) for _ in range(8)][t.start() for t in ts]; [t.join() for t in ts]cents, entries = acc.statement()print(cents, sum(entries) == cents, sum(won) + cents == 1000)Hide the lock as well
| Choice | Problem or benefit |
|---|---|
synchronized methods lock on this | Any caller can lock the same object and stop you |
| Private lock object | Only your methods can hold it |
| Calling a listener while holding the lock | The listener may wait for another lock: deadlock |
| Returning a view of a guarded map | The reader reads without the lock. Return a snapshot made under the lock |
get and set both locked | Each is safe, x.set(x.get() + 1) is not. Offer add(1) |
The trade-off
Coarse methods such as withdraw are safe and fixed. If callers need free combinations, offer a method that takes a function and runs it under the lock (update(f)), and say that f must be short and must not call out. Or make the state an immutable value and swap it with compare and set. More in Correctness and Monitor.