Thread Synchronization
}When multiple threads share anobject and it is modified by one or more of them, indeterminate results may occurunless access to the shared object is managed properly.
}The problem can be solved by giving only one thread at a time exclusive accessto code that manipulates the shared object.
◦During that time, other threads desiring to manipulate the object are kept waiting.
◦When the thread with exclusive access to the object finishes manipulating it, one ofthe threads that was waiting is allowed to proceed.
}This process, called thread synchronization, coordinates access to shared data by multiple concurrent threads.◦Ensures that each thread accessing a shared object excludes all other threads from doing so simultaneously—this is called mutual exclusion.
}A common way to perform synchronization is to use Java’s built-in monitors.
◦Every object has a monitor and a monitor lock (or intrinsiclock).◦Can be held by a maximum of only one thread at any time.
◦A thread must acquire the lock before proceeding with the operation.◦Other threads attempting to performan operation that requires the same lock will be blocked.
}To specify that a thread must holda monitor lock to execute a block of code, the code should be placed in a synchronized statement.
◦Said to be guarded by the monitor lock
}The synchronized statements are declared using the synchronized keyword:
synchronized (object)
{
statements
} //end synchronized statement
}where object is the object whose monitor lock will be acquired◦objectis normally this if it’s the object in which the synchronized statement appears.
}When a synchronized statement finishes executing, the object’s monitor lock is released.
}Java also allows synchronized methods.
.

