| Threads of Control

## Monitors

> The Java language and runtime system support thread synchronization through the use of monitors, which were first outlined in C. A. R. Hoare's article Communicating Sequential Processes (Communications of the ACM, Vol. 21, No. 8, August 1978, pp. 666-677). In general, a monitor is associated with a specific data item (a condition variable) and functions as a lock on that data. When a thread holds the monitor for some data item, other threads are locked out and cannot inspect or modify the data.

> The code segments within a program that access the same data from within separate, concurrent threads are known as critical sections. In the Java language, you mark critical sections in your program with the `synchronized` keyword.

> Note: Generally, critical sections in Java programs are methods. You can mark smaller code segments as synchronized. However, this violates object-oriented paradigms and leads to confusing code that is difficult to debug and maintain. For the majority of your Java programming purposes, it's best to use `synchronized` only at the method level.

> In the Java language, a unique monitor is associated with every object that has a synchronized method. The CubbyHole class for the Producer/Consumer example introduced on the previous page has two synchronized methods: the `put()` method, which is used to change the value in the CubbyHole, and the `get()` method, which is used to retrieve the current value. Thus the system associates a unique monitor with every instance of CubbyHole.

> Here's the source for the CubbyHole object. The bold code elements provide for thread synchronization:

> >     class CubbyHole {
> >         private int contents;
> >         private boolean available = false;

> >         public synchronized int get() {
> >             while (available == false) {
> >                 try {
> >                     wait();
> >                 } catch (InterruptedException e) {
> >                 }
> >             }
> >             available = false;
> >             notifyAll();
> >             return contents;
> >         }

> >         public synchronized void put(int value) {
> >             while (available == true) {
> >                 try {
> >                     wait();
> >                 } catch (InterruptedException e) {
> >                 }
> >             }
> >             contents = value;
> >             available = true;
> >             notifyAll();
> >         }
> >     }

> The `CubbyHole` has two private variables: `contents`, which is the current contents of the CubbyHole, and the boolean variable `available`, which indicates whether the CubbyHole contents can be retrieved. When `available` is true the Producer has just put a new value in the CubbyHole and the Consumer has not yet consumed it. The Consumer can consume the value in the CubbyHole only when `available` is true.

> Because CubbyHole has synchronized methods, Java provides a unique monitor for each instance of CubbyHole (including the one shared by the Producer and the Consumer). Whenever control enters a synchronized method, the thread that called the method acquires the monitor for the object whose method has been called. Other threads cannot call a synchronized method on the same object until the monitor is released.

> Note: Java Monitors Are Re-entrant. That is, the same thread can call a synchronized method on an object for which it already holds the monitor, thereby re-acquiring the monitor.

> Thus, whenever the Producer calls the CubbyHole's `put()` method, the Producer acquires the monitor for the CubbyHole, thereby preventing the Consumer from calling the CubbyHole's `get()` method. (The `wait()` method temporarily releases the monitor as you'll see later.)

> >     public synchronized void put(int value) {
> >             // monitor has been acquired by the Producer
> >         while (available == true) {
> >             try {
> >                 wait();
> >             } catch (InterruptedException e) {
> >             }
> >         }
> >         contents = value;
> >         available = true;
> >         notifyAll();
> >             // monitor is released by the Producer
> >     }

> When the `put()` method returns, the Producer releases the monitor thereby unlocking the CubbyHole.

> Conversely, whenever the Consumer calls the CubbyHole's `get()` method, the Consumer acquires the monitor for the CubbyHole thereby preventing the Producer from calling the `put()` method.

> >     public synchronized int get() {
> >             // monitor has been acquired by the Consumer
> >         while (available == false) {
> >             try {
> >                 wait();
> >             } catch (InterruptedException e) {
> >             }
> >         }
> >         available = false;
> >         notifyAll();
> >         return contents;
> >             // monitor is released by the Consumer
> >     }

> The acquisition and release of a monitor is done automatically and atomically by the Java runtime system. This ensures that race conditions cannot occur in the underlying implementation of the threads, ensuring data integrity.

> Try this: Remove the lines that are shown in bold in the listing of the CubbyHole class shown above. Recompile the program and run it again. What happened? Because no explicit effort has been made to synchronize the Producer and Consumer threads, the Consumer consumes with reckless abandon and gets a whole bunch of zeros instead of getting each integer between 0 and 9 exactly once.

| Threads of Control