Lost updates without a lock
Print unsafe on a multi-core JDK and it's usually below 200000 and different each run. The program only prints facts that are always true, so the expected output is fixed.
When two threads update shared data at the same time without coordination, updates get lost: a race condition. synchronized makes a block or method run by one thread at a time (mutual exclusion) and makes its changes visible to the next thread that takes the same lock.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make a thread-safe counter class with increment and get, and use four threads adding 1000 each.
Explain why if (!list.contains(x)) list.add(x); on a Collections.synchronizedList is still unsafe, and fix it.
Explain it without notes
Why does count++ lose updates when two threads run it, and how do you fix it?
What two guarantees does synchronized give?
Why is a private final lock object better than synchronizing on this?
Expected output
safe counter: 200000
unsafe counter is at most 200000: true