Yurttas/PL/OOL/Java/F/07/04/RWMonitor.java
Jump to navigation
Jump to search
1/**
2 * Copyright(C) 1998
3 * All Rights Reserved. Salih Yurttas, ZCubes, BitsOfCode Software Systems, Inc..
4 *
5 * Permission to use, copy, modify, and distribute this
6 * software and its documentation for EDUCATIONAL purposes
7 * and without fee is hereby granted provided that this
8 * copyright notice appears in all copies.
9 *
10 * @date : January 1, 1998.
11 * @author : Salih Yurttas.
12 */
13
14
15public class RWMonitor {
16
17 private int nReaders=0;
18 private int nWriters=0;
19
20 private ReadWriteMutex readerMutex = new ReadWriteMutex();
21 private ReadWriteMutex writerMutex = new ReadWriteMutex();
22
23 private synchronized boolean readable() {
24 if(nWriters>0)
25 return false;
26
27 nReaders++;
28
29 return true;
30 }
31
32 private synchronized boolean writable() {
33 nWriters++;
34
35 if(nWriters>1)
36 return false;
37
38 if(nReaders>0)
39 return false;
40
41 return true;
42 }
43
44 public void startRead(){
45 while(!readable()){
46 try {
47 readerMutex.mutWait();
48 }
49 catch(InterruptedException iE) {}
50 }
51 }
52
53 public synchronized void endRead() {
54 nReaders--;
55
56 if(nReaders==0)
57 if(nWriters>0)
58 writerMutex.mutNotify();
59 }
60
61 public void startWrite() {
62 if(!writable())
63 try {
64 writerMutex.mutWait();
65 }
66 catch(InterruptedException iE){}
67 }
68
69 public synchronized void endWrite() {
70 nWriters--;
71 if(nWriters>0)
72 writerMutex.mutNotify();
73 else
74 readerMutex.mutNotifyAll();
75 }
76
77}