A counter in the Heap
The Heap holds the objects and all threads share it: Counter lives there. Each thread, instead, will get its own Stack with its local variables.
The Heap holds the objects and all threads share it: Counter lives there.
Each thread, instead, will get its own Stack with its local variables.
The Heap holds the objects and all threads share it: Counter lives there. Each thread, instead, will get its own Stack with its local variables.
In main, new Thread(...) creates two threads for c.increment().
Freshly created, t1 and t2 are NEW: they run nothing yet.
start() launches each thread; run() would run on the main thread itself.
In main, new Thread(...) creates two threads for c.increment(). Freshly created, t1 and t2 are NEW: they run nothing yet. start() launches each thread; run() would run on the main thread itself.
count++ is not atomic: read, add 1 and write.
Thread 1 reads 0; the scheduler hands the turn to thread 2.
Thread 2 also reads 0: both copied the same value.
count++ is not atomic: read, add 1 and write. Thread 1 reads 0; the scheduler hands the turn to thread 2. Thread 2 also reads 0: both copied the same value.
Each thread adds 1 to its copy: both compute 1.
Thread 1 writes 1; thread 2 writes 1 on top of it.
A race condition: two increments and one lost update.
Each thread adds 1 to its copy: both compute 1. Thread 1 writes 1; thread 2 writes 1 on top of it. A race condition: two increments and one lost update.
Back to count = 0, now with synchronized on increment().
To enter, thread 1 takes the object’s lock (its monitor).
Thread 2 finds the lock taken and waits outside.
Back to count = 0, now with synchronized on increment(). To enter, thread 1 takes the object’s lock (its monitor). Thread 2 finds the lock taken and waits outside.
Thread 1 reads 0, writes 1 and releases the lock on its way out.
Then thread 2 enters: it reads 1 and writes 2. Both increments persist.
That is mutual exclusion: one thread at a time.
Thread 1 reads 0, writes 1 and releases the lock on its way out. Then thread 2 enters: it reads 1 and writes 2. Both increments persist. That is mutual exclusion: one thread at a time.
A thread per task is costly: newFixedThreadPool(2) keeps two threads ready.
submit() queues four tasks and the same two threads are reused.
shutdown() closes the pool, awaitTermination waits and 4 is printed.
A thread per task is costly: newFixedThreadPool(2) keeps two threads ready. submit() queues four tasks and the same two threads are reused. shutdown() closes the pool, awaitTermination waits and 4 is printed.
Threads share the Heap: without control, count++ loses updates.
synchronized lets one thread in at a time; a pool reuses a few threads.
Threads share the Heap: without control, count++ loses updates. synchronized lets one thread in at a time; a pool reuses a few threads.