thread, lock, monitor

thread synchronization A monitor is like a building that contains one special room that can be occupied by only one thread at a time. The room usually contains some data. From the time a thread enters this room to the time it leaves, it has exclusive access to any data in the room.
  • Entering the monitor building is called "entering the monitor."
  • Entering the special room inside the building is called "acquiring the monitor."
  • Occupying the room is called "owning the monitor,"
  • and leaving the room is called "releasing the monitor."
  • Leaving the entire building is called "exiting the monitor."
In addition to being associated with a bit of data, a monitor is associated with one or more bits of code, which in this book will be called monitor regions. To implement the mutual exclusion capability of monitors, the Java virtual machine associates a lock (sometimes called a mutex) with each object and class. A lock is like a privilege that only one thread can "own" at any one time. Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can obtain a lock on the same data until the thread that owns the lock releases it. Note that as a Java programmer, you never explicitly lock an object. Object locks are internal to the Java virtual machine. In your Java programs, you identify the monitor regions of your program by writing synchronized statements and methods. As the Java virtual machine runs your program, it automatically locks an object or class every time it encounters a monitor region. We have seen that critical sections are guarded by monitors and only the thread which has a lock associated with that monitor can access the resources in that critical section. In simple terms, consider a synchronized method or a synchronized block of code. Any thread before executing that code takes the lock over the object, the object in case of the synchronized method is the instance on which the synchronized method is called; in case of a synchronized block, it could any other object whose reference is given there. For example, synchronized (anyObject) { }.