~/ learn/ comp-348/ cards/ Synchronization, and choosing what to lock
1 of 5

Lock the shared Writer for the whole record

Lock the shared Writer for the whole record

Answer

public void log(String record) throws IOException { String stamp = timestamp(); // outside the lock: no shared state synchronized (out) { // the shared object, not `this` out.write(stamp); out.write(' '); out.write(record); out.write("\r\n"); } }

The block is exactly as wide as the invariant: one record, indivisible. Formatting the timestamp touches nothing shared, so it stays outside and shortens the time the monitor is held.

Harold 4e ch3 §Synchronization

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e75e5f2c-a0d0-4845-8a8a-9c0edd9bab83/flashcard utf-8 LF