| Threads of Control

## Multithreaded Programs

> #### Synchronizing Threads

> > Often, threads need to share data. For example, suppose you have a thread that writes data to a file while, at the same time, another thread is reading data from that same file. When your threads share information, you need to synchronize the threads to get the desired results.

> #### Fairness, Starvation, and Deadlock

> > If you write a program in which several concurrent threads are competing for resources, you must take precautions to ensure fairness. A system is fair when each thread gets enough access to limited resource to make reasonable progress. A fair system prevents starvation and deadlock. Starvation occurs when one or more threads in your program is blocked from gaining access to a resource and thus cannot make progress. Deadlock is the ultimate form of starvation; it occurs when two or more threads are waiting on a condition that cannot be satisfied. Deadlock most often occurs when two (or more) threads are each waiting for the other(s) to do something.

> > Deadlock and the Dining Philosophers uses the dining philosophers problem to illustrate deadlock. It also discusses ways you can prevent deadlock.

> #### Volatile

> > Your programs can modify member variables outside the protection of a synchronized method or a synchronized block and you can declare that the member variable is volatile.

> > If a member variable is declared to be volatile, the Java runtime system uses this information to ensure that the variable is loaded from memory before each use, and stored to memory after each use. This ensures that the value of the variable is consistent and coherent throughout the program.

> > the JDK 1.0 version of the Java runtime system ignores the `volatile` marker.

| Threads of Control