Friday, 16 September 2016

Race condition in multithreading

"When more than one thread try to access same resource without synchronization causes race condition."

So we can solve race condition by using either synchronized block or synchronized method. When no two threads can access same resource at a time phenomenon is also called as mutual exclusion.

Example (Train ticket booking)-
Let's say there is only 1 ticket available in train, and two passengers are trying to book that ticket at same time without synchronization.
It might happen that both might end up booking up ticket, though only ticket was available, which is of course going to create problem.
But if synchronization was there only of them would have been able to book ticket.


Program to show that without synchronization problems will happen when  2 passengers try to book train ticket, dat too when only 1 ticket was available
class TicketBooking implements Runnable{
   int ticketsAvailable=1;
  
   public void run(){
         
          System.out.println("Waiting to book ticket for : "+Thread.currentThread().getName());
          if(ticketsAvailable>0){
                 System.out.println("Booking ticket for : "+Thread.currentThread().getName());
                
                 //Let's say system takes some time in booking ticket (here we have taken 1 second time)
                 try{
                       Thread.sleep(1000);
                 }catch(Exception e){}
                  
                 ticketsAvailable--;
                 System.out.println("Ticket BOOKED for : "+ Thread.currentThread().getName());
                 System.out.println("currently ticketsAvailable = "+ticketsAvailable);
          }
          else{
                 System.out.println("Ticket NOT BOOKED for : "+ Thread.currentThread().getName());
          }
         
         
   }
  
}
public class MyClass {
   public static void main(String args[])
   {
          TicketBooking obj=new TicketBooking();
         
          Thread thread1=new Thread(obj,"Passenger1 Thread");
          Thread thread2=new Thread(obj,"Passenger2 Thread");
         
          thread1.start();
          thread2.start();
         
   }
}
/*OUTPUT
Waiting to book ticket for : Passenger1 Thread
Waiting to book ticket for : Passenger2 Thread
Booking ticket for : Passenger1 Thread
Booking ticket for : Passenger2 Thread
Ticket BOOKED for : Passenger1 Thread
currently ticketsAvailable = 0
Ticket BOOKED for : Passenger2 Thread
currently ticketsAvailable = -1
*/
If we note the above program,
first Passenger1 Thread and Passenger2 Thread waited to book tickets.
Than, both threads tried to check the available ticket count and it was 1.
Both threads were able to book ticket.
And ultimately available ticket was reduced to -1, which is practically impossible, tickets count can never dip below 0.

Above problem can be solved using synchronization.

No comments:

Post a Comment