/* Copyright (c) 2004 Joseph Gleason Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Current versions of this and other code can be downloaded at: http://gleason.cc/ */ package cc.glsn; import java.io.Serializable; public class RWMonitor implements Serializable { /** * Comment for serialVersionUID */ private static final long serialVersionUID = 1L; private int WaitingReaders; //Waiting Readers private int RunningReaders; //Running Readers private int WaitingWriters; //Waiting Writers private int RunningWriters; //Running Writers public RWMonitor() { WaitingReaders=0; RunningReaders=0; WaitingWriters=0; RunningWriters=0; } public void PrintState() { } public synchronized void Read() { WaitingReaders++; while ((WaitingWriters > 0) || (RunningWriters > 0)) { try { this.wait(); } catch(Exception e) {e.printStackTrace();} } //this.notifyAll(); RunningReaders++; } /** Non-blocking read try returns true is successfull or false if not successfull UnRead() needs to be done if returns true */ public synchronized boolean InstantRead() { if ((WaitingWriters==0) && (RunningWriters==0)) { WaitingReaders++; RunningReaders++; return true; } return false; } public synchronized void UnRead() { RunningReaders--; WaitingReaders--; this.notifyAll(); } public synchronized void Write() { WaitingWriters++; while ((RunningWriters > 0) || (RunningReaders > 0)) { try { this.wait(); } catch(Exception e) {e.printStackTrace();} } RunningWriters++; } public synchronized void UnWrite() { RunningWriters--; WaitingWriters--; this.notifyAll(); } }