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