Saturday, January 22, 2011

Part 6: java.util.concurrent - Lock and Condition Object



Today in next part of the series we will talk about How to communicate among threads using Lock and Condition Objects.


In traditional Java - If we need to communicate among threads, we syncronize code and use "wait" and "notify" methods  of Object class.
From Java 5.0 and above - Lock interface provides an easier implmentation for synchronization and Condition class can be used to wait and notify threads.


Lock has several important methods such as "lock", "tryLock", "lockInterruptibly" etc, whereas Condition has "await", "signal", 'signalAll" etc. In this article we will demonstrate the usage of 3 methods - "lock" (from Lock interface), "await", "signal" (from Condition Class).


Lets try to visualize a scenario here - Assume we have 2 process "Reader" and "Writer". Writer writes on a file and Reader reads from a file. we want to add a listener to writer object so that whenever writer writes anything on a file, "Reader" will be called and it will read the same data. Before we look into codes lets look at the some important points to use Lock and Condition-


1) Lock is an Interface, the most common implementation class is ReentrantLock. Others two are - ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
2) Condition Object is always retrieved from Lock object. For example - Condition condition = lock.newCondition( );
3) One of the best practice to use Lock is-
Lock lockObj = new ReentrantLock( );
                    lockObj.lock( );
                        try{
.... code..
                           }finally{
                      lockObj.unlock( );
                           }
4) condition.await, condition.signal, condition.signalAll methods should only be called once you have acquired the lock by - lockObj.lock( ).
In our example, the design of the class will be something like this -
> One lock Object == fileLock
> One condition Object = condition = fileLock.newCondition


Pseudo code for Writer Thread 
// GET the LOCK
try{
  // -- In  the Loop untill EXIT---
     //Write on the file
     // Signal the READER
     //If EXIT signal then exit else "WAIT for READER to SIGNAL"
 }finally{
  // RELEASE the LOCK
 }
pseudo code for Reader Thread 
// GET the LOCK
try{
  // -- In  the Loop untill EXIT---
     //Read from the file
     // Signal the WRITER
     // If EXIT signal - then exit else "WAIT for WRITER to SIGNAL"
 }finally{
  // RELEASE the LOCK
 }


package com.jovialjava.blog.threads;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
 
 private static final String fileName = "LockExample.txt";
 private static final String EXIT_FLAG = "BYE";
 private static final int NO_OF_LINES = 10;
 private static final Lock fileLock = new ReentrantLock();
 private static final Condition condition = fileLock.newCondition();
 private static final ExecutorService executorPool=Executors.newFixedThreadPool(2);
 
 public static void main(String...args){  
  Runnable fileWriter = new FileWrite();
  Runnable fileReader = new FileRead();  
  executorPool.submit(fileReader);
  executorPool.submit(fileWriter); 
  executorPool.shutdown();
 }
 
 /**
  * This thread will write on a file and inform the reader thread to
  * read it. If it has not written the EXIT flag then it will go into 
  * wait stage and will wait for READER to signal that it safe to write
  * now. 
  */
 public static class FileWrite implements Runnable{
  
  public void run( ){   
   try{
    fileLock.lock();
   for(int i=0; i< NO_OF_LINES; i++){    
    PrintWriter writer = new PrintWriter(new File(fileName));    
    if(i != NO_OF_LINES - 1){
     int random = new SecureRandom().nextInt();
     System.out.println("WRITER WRITING " + random);
     writer.println(random);
     writer.close();
     //signallng to READER that its safe to read now.
     condition.signal();
     System.out.println("Writer waiting");
     condition.await();
    }else{
     writer.println(EXIT_FLAG);
     System.out.println("WRITER EXITING ");
     writer.close();
     //AS it was an exit flag so no need to wait, just signal the reader.
     condition.signal();
    }   
   }   
   }catch(Exception e){
    System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!EXCEPTION!!!!!!!!!!!!!!!!!!!!!!!!");
    e.printStackTrace();
   }finally{
    fileLock.unlock();
    // Delete the file, require in case if one wants to run demo again.
    File file = new File(fileName);
    file.delete();
    try{
     file.createNewFile();
    }catch(Exception e){}
   }
  }
 } 
 /**
  * This thread will read from the file and inform the writer thread to
  * write again. If it has not read the EXIT flag then it will go into 
  * wait stage and will wait for WRITER to signal that it safe to read
  * now. 
  */
 public static class FileRead implements Runnable{
    
  public void run( ){
   String data = null;   
   fileLock.lock();   
  try{   
   while(true){    
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    data = reader.readLine();
    System.out.println("READ DATA - " + data);        
    reader.close();
    if(data == null || !data.equals(EXIT_FLAG)){
     condition.signalAll();
     System.out.println("Reader Waiting");
     condition.await();
    }else{
     System.out.println("READER EXITING");
     condition.signal();
     break;
    }    
   }
   }catch(Exception e){
    System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!EXCEPTION!!!!!!!!!!!!!!!!!!!!!!!!");
    e.printStackTrace();
   }finally{
    fileLock.unlock();
   }
  }
 }
}
>

7 comments:

Anonymous said...

This program does not work. File Reader will throw an exception saying FileNotFoundException.

Anonymous said...

It Works if you create the file before ...
Thanks nice work ....

Owens Hsu said...

This program will cause deadlock contingently.

Print locking and unlocking messages before "fileLock.lock();" and "fileLock.unlock();".

Then it turns out that intermittently writer and reader might both acquire the lock before anyone releasing it.

Owens Hsu said...

Sorry the real cause of the deadlock is that writer waits but reader has already exited, because the first read by reader is "BYE".

Anyone knows why and how to fix it?

swati aole said...

Not sure if it really affects the thread sequence, how we submit it to thread pool, but I changed the sequence in main method like this:

executorPool.submit(fileWriter);
executorPool.submit(fileReader);


and its working perfectly alright.

Santanu Nandi said...

Change the below line:
if(data == null || !(data==EXIT_FLAG ))

to as follows:

if(data == null || !(data.equals(EXIT_FLAG))).

Since String comparison with == was false it was not going into the else part and the Reader was not getting closed.

Eric Simmons said...

Great and Useful Article.

Online Java Training

Online Java Training from India

Java Online Training

Online Java Training India

Java Training Institutes in Chennai

Java Course in Chennai

Java Training in Chennai

Java Interview Questions

Java Tutorials

Core Java Interview Questions