Synchronization in Java
Overview
Synchronization is the process by which we control the accessibility of multiple threads for a particular resource. With synchronization only one thread at a time can execute a particular method or block of code. Without synchronization we can face the problem of data inconsistency and thread interference.
Disadvantages of Synchronization
- Synchronization can increase the waiting time of application due to synchronization of multiple threads.
- At times, synchronization can create performance issues.
Types of Synchronization
- Process Synchronization - not present in Java multithreading.
- Thread Synchronization -
- Mutual Exclusive - It can be achieved by 3 ways
- By synchronized method
synchronized void bookSeats(int seats) {
if (seats <= total_seats) {
System.out.println(seats + " seats are booked successfully!!!");
total_seats = total_seats - seats;
System.out.println("Seats left: " + total_seats);
} else {
System.out.println("Sorry all the seats are booked");
System.out.println("Seats left: " + total_seats);
}
}
- By synchronized block
synchronized (this) {
if (seats <= total_seats) {
System.out.println(seats + " seats are booked successfully!!!");
total_seats = total_seats - seats;
System.out.println("Seats left: " + total_seats);
} else {
System.out.println("Sorry all the seats are booked");
System.out.println("Seats left: " + total_seats);
}
}
- By static synchronization
- Cooperation - It can also by achieved by 3 ways
- wait()
- notify()
- notifyAll()
Example of data inconsistency and thread interference.
public class BookTheatre {
int total_seats = 10;
void bookSeats(int seats) {
if (seats <= total_seats) {
System.out.println(seats + " seats are booked successfully!!!");
total_seats = total_seats - seats;
System.out.println("Seats left: " + total_seats);
} else {
System.out.println("Sorry all the seats are booked");
System.out.println("Seats left: " + total_seats);
}
}
}
public class MovieBookApp extends Thread {
private static BookTheatre bookTheatre;
private int seats;
@Override
public void run() {
bookTheatre.bookSeats(seats);
}
public static void main(String[] args) {
bookTheatre = new BookTheatre(); // Here the property bookTheatre of MovieBookApp is static
/*Object for Deepak*/
MovieBookApp deepak = new MovieBookApp();
deepak.seats = 7;
deepak.start();
/*Object for Amit*/
MovieBookApp amit = new MovieBookApp();
amit.seats = 8;
amit.start();
}
}
Output - Here Amit shouldn't get 8 seats of the movie because there were total only 10 seats available and out of them 7 seats were booked by Deepak. It's a clear example of miscalculation.
7 seats are booked successfully!!!
8 seats are booked successfully!!!
Seats left: 3
Seats left: -5
Comments
Post a Comment