Synchronized

4 April 1996

Each thread is associated with some object. As the thread runs, it has exclusive use of the instance field variables within that object. If there are multiple instances of the thread class running at the same time, they may need to coordinate access to datasets, databases, sessions, and even simple counters.

Any object may contain data that will, at some time, be of interest to some of the threads. The data could be public, allowing the code in the thread class to access the field directly. Those who scrupulously follow the guidelines of Object Oriented design will not expose instance data to public access, but will require code in other classes to call a public method to gain indirect and controlled access to the object fields.

A method can be declared with the synchronized keyword. When such a method is called, it acquires what system programmers call a lock that provides this thread with temporary exclusive access to the data in the current object. The method can decrease one counter, increase another, move data around on queues, and be confident that during these changes no other thread is using any of the fields that are being changed. When the synchronized method returns to its caller, the lock is freed and other threads can proceed with their access to the object.

The lock governs the entire object, and all of the synchronized methods defined in the class. A thread calling any synchronized method blocks access to all of the other synchronized methods for the object until it is done.

Although synchronized methods are the simplest programming option for new user-defined classes, the program may have to deal with library classes and code written for other non-threaded application. It would be tedious to have to override all the existing methods with new versions that synchronize access. So an alternative technique is to update fields and call unsynchronized methods from within a block that acquires the lock for an object explicitly:

synchronized (System.out) {
System.out.println("Please send more money");
}

Back PCLT

Copyright 1996 PC Lube and Tune -- Java H. Gilbert

This document generated by SpHyDir, another fine product of PC Lube and Tune.