A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong. : Lock Synchronize « Threads « Java






A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong.

    

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 * 
 * ---------------------
 * ReaderWriterLock.java
 * ---------------------
 *
 * $Id: ReaderWriterLock.java,v 1.3 2005/10/18 13:18:34 mungady Exp $
 *
 * Changes
 * -------
 * 29-Jan-2003 : Added standard header (DG);
 *
 */

import java.util.ArrayList;
import java.util.Iterator;

/**
 * A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong.
 * 
 * @author Scott Oak and Henry Wong
 */
public class ReaderWriterLock {

  /**
   * A node for the waiting list.
   * 
   * @author Scott Oak and Henry Wong
   */
  private static class ReaderWriterNode {

    /** A reader. */
    protected static final int READER = 0;

    /** A writer. */
    protected static final int WRITER = 1;

    /** The thread. */
    protected Thread t;

    /** The state. */
    protected int state;

    /** The number of acquires. */
    protected int nAcquires;

    /**
     * Creates a new node.
     * 
     * @param t
     *          the thread.
     * @param state
     *          the state.
     */
    private ReaderWriterNode(final Thread t, final int state) {
      this.t = t;
      this.state = state;
      this.nAcquires = 0;
    }

  }

  /** The waiting threads. */
  private ArrayList waiters;

  /**
   * Default constructor.
   */
  public ReaderWriterLock() {
    this.waiters = new ArrayList();
  }

  /**
   * Grab the read lock.
   */
  public synchronized void lockRead() {
    final ReaderWriterNode node;
    final Thread me = Thread.currentThread();
    final int index = getIndex(me);
    if (index == -1) {
      node = new ReaderWriterNode(me, ReaderWriterNode.READER);
      this.waiters.add(node);
    } else {
      node = (ReaderWriterNode) this.waiters.get(index);
    }
    while (getIndex(me) > firstWriter()) {
      try {
        wait();
      } catch (Exception e) {
        System.err.println("ReaderWriterLock.lockRead(): exception.");
        System.err.print(e.getMessage());
      }
    }
    node.nAcquires++;
  }

  /**
   * Grab the write lock.
   */
  public synchronized void lockWrite() {
    final ReaderWriterNode node;
    final Thread me = Thread.currentThread();
    final int index = getIndex(me);
    if (index == -1) {
      node = new ReaderWriterNode(me, ReaderWriterNode.WRITER);
      this.waiters.add(node);
    } else {
      node = (ReaderWriterNode) this.waiters.get(index);
      if (node.state == ReaderWriterNode.READER) {
        throw new IllegalArgumentException("Upgrade lock");
      }
      node.state = ReaderWriterNode.WRITER;
    }
    while (getIndex(me) != 0) {
      try {
        wait();
      } catch (Exception e) {
        System.err.println("ReaderWriterLock.lockWrite(): exception.");
        System.err.print(e.getMessage());
      }
    }
    node.nAcquires++;
  }

  /**
   * Unlock.
   */
  public synchronized void unlock() {

    final ReaderWriterNode node;
    final Thread me = Thread.currentThread();
    final int index = getIndex(me);
    if (index > firstWriter()) {
      throw new IllegalArgumentException("Lock not held");
    }
    node = (ReaderWriterNode) this.waiters.get(index);
    node.nAcquires--;
    if (node.nAcquires == 0) {
      this.waiters.remove(index);
    }
    notifyAll();
  }

  /**
   * Returns the index of the first waiting writer.
   * 
   * @return The index.
   */
  private int firstWriter() {
    final Iterator e = this.waiters.iterator();
    int index = 0;
    while (e.hasNext()) {
      final ReaderWriterNode node = (ReaderWriterNode) e.next();
      if (node.state == ReaderWriterNode.WRITER) {
        return index;
      }
      index += 1;
    }
    return Integer.MAX_VALUE;
  }

  /**
   * Returns the index of a thread.
   * 
   * @param t
   *          the thread.
   * 
   * @return The index.
   */
  private int getIndex(final Thread t) {
    final Iterator e = this.waiters.iterator();
    int index = 0;
    while (e.hasNext()) {
      final ReaderWriterNode node = (ReaderWriterNode) e.next();
      if (node.t == t) {
        return index;
      }
      index += 1;
    }
    return -1;
  }

}

   
    
    
    
  








Related examples in the same category

1.Thread: Dining Philosophers
2.Synchronizing on another objectSynchronizing on another object
3.Operations that may seem safe are not, when threads are presentOperations that may seem safe are not, when threads are present
4.Synchronizing blocks instead of entire methodsSynchronizing blocks instead of entire methods
5.Boolean lockBoolean lock
6.Static synchronized blockStatic synchronized block
7.Thread notifyThread notify
8.Thread deadlockThread deadlock
9.Synchronize methodSynchronize method
10.Threads joinThreads join
11.Static synchronizeStatic synchronize
12.No synchronizeNo synchronize
13.Thread synchronizationThread synchronization
14.Synchronized Block demoSynchronized Block demo
15.Interruptible Synchronized Block Interruptible Synchronized Block
16.SignalingSignaling
17.Simple Object FIFOSimple Object FIFO
18.Object FIFOObject FIFO
19.Byte FIFOByte FIFO
20.Daemon Lock
21.Determining If the Current Thread Is Holding a Synchronized Lock
22.Handle concurrent read/write: use synchronized to lock the data
23.Lock for read and write
24.Read Write Lock
25.Coordinates threads for multi-threaded operations
26.Invoke a series of runnables as closely to synchronously as possible
27.This program shows how multiple threads can safely access a data structure, using synchronized methods
28.This program shows data corruption when multiple threads access a data structure.
29.Stores a single object for the producer/consumer pattern and takes care of thread synchronization.
30.The BooleanLock class provides a useful encapsulation of a boolean variable that is easily and safely accessed from multiple theads.