Thready Safety & Synchronized
This lesson explains thread-safety and the use of the synchronized keyword.
We'll cover the following...
With the abstract concepts discussed, we'll now turn to the concurrency constructs offered by Java and use them in later sections to solve practical coding problems.
Thread Safe
A class and its public APIs are labelled as thread safe if multiple threads can consume the exposed APIs without causing race conditions or state corruption for the class. Note that composition of two or more thread-safe classes doesn't guarantee the resulting type to be thread-safe.
Synchronized
Java’s most fundamental construct for thread synchronization is the synchronized
keyword. It can be used to restrict access to critical sections one thread at a time.
Each object in Java has an entity associated with it called the "monitor lock" or just monitor. Think of it as an exclusive lock. Once a thread gets hold of the monitor of an object, it has exclusive access to all the methods marked as synchronized. No other thread will be allowed to invoke a method on the object that is marked as ...