The Java Language Environment

 
CONTENTS | PREV | NEXT The Java Language Environment

7.2 Integrated Thread Synchronization

Java supports multithreading at the language (syntactic) level and via support from its run-time system and thread objects. At the language level, methods within a class that are declared synchronized do not run concurrently. Such methods run under control of monitors to ensure that variables remain in a consistent state. Every class and instantiated object has its own monitor that comes into play if required.

Here are a couple of code fragments from the sorting demonstration in the HotJava web browser. The main points of interest are the two methods stop and startSort, which share a common variable called kicker (it kicks off the sort thread):

public synchronized void stop() {
              
if (kicker != null) {
kicker.stop();
kicker = null;
}
}
private synchronized void startSort() {
              
if (kicker == null || !kicker.isAlive()) {
kicker = new Thread(this);
kicker.start();
}
}
The stop and startSort methods are declared to be synchronized--they can't run concurrently, enabling them to maintain consistent state in the shared kicker variable. When a synchronized method is entered, it acquires a monitor on the current object. The monitor precludes any other synchronized methods in that object from running. When a synchronized method returns by any means, its monitor is released. Other synchronized methods within the same object are now free to run.

If you're writing Java applications, you should take care to implement your classes and methods so they're thread-safe, in the same way that Java run-time libraries are thread-safe. If you wish your objects to be thread-safe, any methods that may change the values of instance variables should be declared synchronized. This ensures that only one method can change the state of an object at any time. Java monitors are re-entrant: a method can acquire the same monitor more than once, and everything will still work.


CONTENTSPREVNEXT
jdk-comments@java.sun.com
Copyright © 1997 Sun Microsystems, Inc. All Rights Reserved.
Left Curve
Java SDKs and Tools
Right Curve
Left Curve
Java Resources
Right Curve
JavaOne Banner Java 8 banner (182)