Java-Synchronized Block

Synchronized Block

Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by you, but by a third party, and you do not have access to the source code. Thus, you can’t add synchronized to the appropriate methods within the class. How can access to an object of this class by synchronized? Fortunately, the solution to this problem is quite easy. You simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized block :

Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor. The following program is an improved version of the previous program, using a synchronized block within the run( ) method. Here, the bookTicket( ) method is not modified by synchronized. Instead, the synchronized statement is used inside TicketBookingThread’s run( ) method. This causes the same correct output as the previous program, because each thread waits for the prior one to finish before proceeding.



Program Source

class TicketCounter{
    int availableSeats = 2;
    void bookTicket(String pname,int numberOfSeats)
            System.out.println(pname+" : "+numberOfSeats+" Seats Booking Success");
            System.out.println(pname+" : Seats Not Available");

class TicketBookingThread extends Thread{

    TicketCounter tc;
    String name;
    int seats;
    TicketBookingThread(TicketCounter t,String pname,int pseats)
        tc = t;
        name = pname;
        seats = pseats;

    public void run()
            tc.bookTicket(name, seats);

public class Javaapp {

    public static void main(String[] args) {
        TicketCounter tc = new TicketCounter();
        TicketBookingThread th1 = new TicketBookingThread(tc,"Kannan",2);
        TicketBookingThread th2 = new TicketBookingThread(tc,"Sarava",2);

Leave a Comment