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.
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 the method's class as monitor object, while synchronized instance methods use this
. So, the previous code would be equivalent to:
public void setGadget(Gadget g) { synchronized(this) { this.gadget = g; } }