Synchronized methods and blocks -II

Synchronized Method

Synchronize methods are very useful specially when state of an object is changed by class member method which can corrupt object state if executed concurrently. Consider example discussed in previous article, can be found from here, where class counter have two methods increment and decrement. One thread is incrementing whereas other is decrementing counter. If several threads have to share the same counter, then one thread may not be able to increment counter while another decrementing counter. Integerity of counter is maintained in the face of several threads accessing the state of same counter.

After running program with synchronized method increment() and decrement() avoids race of condition. Method sleep() does not release any lock of current thread. It release lock once synchronized method exits.

Possible output is :

Increased : 0
Increased : 1
Increased : 2
Increased : 3
Increased : 4
Increased : 5
Increased : 6
Increased : 7
Increased : 8
Increased : 9
Exit from main().
Decreased : 10
Decreased : 9
Decreased : 8
Decreased : 7
Decreased : 6
Decreased : 5
Decreased : 4
Decreased : 3
Decreased : 2
Decreased : 1

No Responses