Example of Synchronized Method in Java
Example of Synchronized Method in Java
Using synchronized keyword along with method is easy just apply synchronized keyword in front of method.
What we need to take care is that static synchronized method locked on class object lock and non static
synchronized method locks on current object (this). So it’s possible that both static and non static java
synchronized method running in parallel. This is the common mistake a naive developer do while writing java
synchronized code.
In this example of java synchronization code is not properly synchronized because both getCount() and setCount()
are not getting locked on same object and can run in parallel which results in getting incorrect count. Here
getCount() will lock in Counter.class object while setCount() will lock on current object (this). To make this code
properly synchronized in java you need to either make both method static or non static or use java synchronized
block instead of java synchronized method.
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
This is a classic example of double checked locking in Singleton. In this example of java synchronized code we
have made only critical section (part of code which is creating instance of singleton) synchronized and saved some
performance because if you make whole method synchronized every call of this method will be blocked while you
only need to create instance on first call. To read more about Singleton in Java see here.
Synchronized Methods
The Java programming language provides two basic synchronization idioms: synchronized
methods and synchronized statements. The more complex of the two, synchronized statements,
are described in the next section. This section is about synchronized methods.
To make a method synchronized, simply add the synchronized keyword to its declaration:
First, it is not possible for two invocations of synchronized methods on the same object to
interleave. When one thread is executing a synchronized method for an object, all other threads
that invoke synchronized methods for the same object block (suspend execution) until the first
thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before
relationship with any subsequent invocation of a synchronized method for the same object. This
guarantees that changes to the state of the object are visible to all threads.