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
public class MExclusion { public static void main(String[] args) { final Counter count = new Counter(); // Shared by the threads. (new Thread("Increment") { // Thread no. 1 public void run() { for(int i =0; i<10; i++) { System.out.println("Increased : " + count.increment()); } } }).start(); (new Thread("Decrement") { // Thread no. 2 public void run() { for(int i =0; i<10; i++) { System.out.println("Decreased : " + count.decrement()); } } }).start(); System.out.println("Exit from main()."); } } class Counter{ int count; Counter(){ count=0; } public int increment(){ //non - synchronized method return count++; } public int decrement(){ //non - synchronized method return count--; } }
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