AlgoViz

Ensuring proper encapsulation

medium 40 min

Private 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)
1000 = 142 x 7 + 6, so 6 cents stay. The statement reads both fields under one lock.
Edit and run it in your browser

Hide the lock as well

ChoiceProblem or benefit
synchronized methods lock on thisAny caller can lock the same object and stop you
Private lock objectOnly your methods can hold it
Calling a listener while holding the lockThe listener may wait for another lock: deadlock
Returning a view of a guarded mapThe reader reads without the lock. Return a snapshot made under the lock
get and set both lockedEach 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.