Monday, October 11, 2010

Example for java.util.concurrent.locks.ReentrantReadWriteLock usage


Let's try the latest sample with another beauty of the java.util.concurrent package :ReentrantReadWriteLock



import java.util.concurrent.locks.*;

public class ReentrantReadWriteLockExample {
    int i = 0;

    public static void main (String[] args) {
        final ReentrantReadWriteLockExample example = new ReentrantReadWriteLockExample();
        final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

        final Runnable r = new Runnable () {
            public void run () {
                while (true) {
                    try {
                        lock.writeLock().lock();
                        //Here is the critical section jobs are being done securely..
                        example.printSomething ();
                        Thread.sleep (1000);
                        lock.writeLock().unlock();
                    } catch (Exception ex) {
                        System.out.println (" -- Interrupted...");
                        ex.printStackTrace ();
                    }
                }
            }
        };

        new Thread (r).start ();
        new Thread (r).start ();
        new Thread (r).start ();
    }

    public void printSomething (){
        i++;
        System.out.println (" -- current value of the i :"+ i);
    }
}

No comments:

Post a Comment