Java API

This section covers the built-in synchronization mechanisms in Java. These are convenient to have as intrinsic mechanisms in the language. There are, however, potential dangers of misusing or overusing Java synchronization mechanisms.

The synchronized keyword

In Java, the keyword synchronized is used to define a critical section. Both code blocks inside a method and entire methods can be synchronized. The following code example illustrates a synchronized method:

public synchronized void setGadget(Gadget g) {
this.gadget = g;
}

As the method is synchronized, only one thread at a time can write to the gadget field in a given object.

In a synchronized method, the monitor object is implicit. Static synchronized methods use the class object of ...

Get Oracle JRockit now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.