When do you synchronize a piece of code?

(Last Updated On: January 1, 2015)

Answer:

When a piece of code is accessed by more than one threads at the same time, we need synchronization.

Reason is that we may get corrupted data, when two threads concurrently attempt to read / write the same memory location.

when one thread changes the state of a shared resource then changes may not become apparent to other threads immediately (or even at all) without proper synch. This means that one thread can’t be reading while another updates it.