2. Synchronized
Inverweaving
JVM split up expressions like count++ up into multiple instructions (read, increment, store)
if two threads invoke count++ on the same object, both might first read the old value, increment separately, and write their respective values. That would increment by 1, not 2 (interweaving)
Solution: synchronized
Prevents multiple threads from running the same block of code at the same time. One thread gets the lock, the others wait their turn.
Without it, if two threads update a shared variable simultaneously, results can be wrong because the operations interleave. For example:
class Counter {
int count = 0;
// Option 1
synchronized void increment() {
count++;
}
// Option 2
void dance() {
// Do some cray non-interfering stuff
synchronized (this) { // any object to lock
count++;
}
}
}