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;@Overridepublic 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
BookTheatreSeatclass which has a total of 10 available seats. -
Inside the
BookTheatreSeatclass, there is a method calledbookSeaton line 4 that books the specified number of seats if available. -
In line 4, the
synchronizedkeyword 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
movieBookingclass is made, which extends thethreadclass. Inside themovieBookingclass, there is a main function in which we initiate two threads namedthreadOneandthreadTwo. These will try to book 7 and 6 seats, respectively. -
Without the
synchronisedkeyword, 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.