Why is synchronization necessary in Java?

Multithreaded programs may often come to a situation where multiple threads try to access the same shared resources and finally produce unfortunate results. Synchronization in Java is the capability to control the access of multiple threads to any shared resources. Therefore, Java synchronization is a better option when you want only one thread to access the shared resource.

Code

To understand synchronization better, let’s look at the code snippet below.

class BookTheatreSeat
{
int totalSeats=10;
synchronized void bookSeat(int seats)
{
if(totalSeats>=seats)
{
System.out.println("seats booked successfully");
totalSeats-=seats;
System.out.println("Seats left:"+totalSeats);
}
else
{
System.out.println("seats not booked");
System.out.println("Seats left:"+totalSeats);
}
}
}
class MovieBooking extends Thread{
int seats;
static BookTheatreSeat bookTheatreSeat;
@Override
public void run() {
super.run();
bookTheatreSeat.bookSeat(seats);
}
public static void main(String[] args) {
bookTheatreSeat=new BookTheatreSeat();
MovieBooking threadOne = new MovieBooking();
threadOne.seats=7;
threadOne.start();
MovieBooking threadTwo = new MovieBooking();
threadTwo.seats=6;
threadTwo.start();
}
}

Explanation

  • In lines 1 to 18, we create a BookTheatreSeat class which has a total of 10 available seats.

  • Inside the BookTheatreSeat class, there is a method called bookSeat on line 4 that books the specified number of seats if available.

  • In line 4, the synchronized keyword is used in the function signature so that the critical section of the code can’t be accessed by multiple threads simultaneously.

  • In line 19, a movieBooking class is made, which extends the thread class. Inside the movieBooking class, there is a main function in which we initiate two threads named threadOne and threadTwo. These will try to book 7 and 6 seats, respectively.

  • Without the synchronised keyword, both the threads would access the critical part of the code at the same time but now the issue has been solved. Now multiple threads can try to access the critical section code without any race conditions.

Free Resources