Synchronized methods and blocks -I

Java threads can share resources like memory space etc. Critical situation arise when only one thread at a time have access to shared resources. To handle similar situations, java provides high level concepts for synchronization to control access to shared resources.

Locks

A lock can be used to synchronize access to shared resources. Any thread can gain acess to shared resources with associated lock by acquiring the lock. One thread can hold the lock at any given time and have access to shared resources which is known as mutual exclusion.
Java classes also have class specific lock which is java.lang.Class object associated with class. For example A java class with name A, the reference A.class donotes this unique class object. The class lock can be used in much the same way as an object lock to implement mutual exclusion. In order to synchronize execution of code, following two methods can be used

  • Synchronized methods
  • Synchronized blocks

Thread example without using synchronized keyword

Possible out is listed as :

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

Further discussion on synchronized methods and blocks will appear in next article.

No Responses