Java Thread How to - Use ReentrantReadWriteLock








Question

We would like to know how to use ReentrantReadWriteLock.

Answer

import java.util.concurrent.locks.ReentrantReadWriteLock;
//from   www.  j  av a  2s.c om
public class Main {
  static final Main instance = new Main();
  int counter = 0;
  ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);

  public void read() {
    while (true) {
      rwl.readLock().lock();
      try {
        System.out.println("Counter is " + counter);
      } finally {
        rwl.readLock().unlock();
      }
      try {
        Thread.currentThread().sleep(1000);
      } catch (Exception ie) {
      }
    }
  }

  public void write() {
    while (true) {
      rwl.writeLock().lock();
      try {
        counter++;
        System.out.println("Incrementing counter.  Counter is " + counter);
      } finally {
        rwl.writeLock().unlock();
      }
      try {
        Thread.currentThread().sleep(3000);
      } catch (Exception ie) {
      }
    }
  }
  public static void main(String[] args) {
      instance.write();
      instance.read();
  }
}

The code above generates the following result.