Previous | Next | Trail Map | Writing Java Programs | 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 need to 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 does not allow for starvation or for deadlock. Starvation occurs when one or more threads in your program is blocked from gaining access to a resource and cannot make progress. Deadlock is the ultimate form of starvation and occurs when two or more threads are waiting on a condition that cannot be satisfied.

The next page, Deadlock and the Dining Philosophers, uses the dining philosophers problem to illustrate deadlock and discusses ways you can prevent it.

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-- Declaring a Volatile Variable(in the Writing Java Programs trail) shows you how to do this.

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.

At this time, the Java runtime system ignores the volatile marker.


Previous | Next | Trail Map | Writing Java Programs | Threads of Control