KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > trading > util > RWLock


1
2 // Copyright (C) 1998-1999
3
// Object Oriented Concepts, Inc.
4

5 // **********************************************************************
6
//
7
// Copyright (c) 1997
8
// Mark Spruiell (mark@intellisoft.com)
9
//
10
// See the COPYING file for more information
11
//
12
// **********************************************************************
13

14 package org.jacorb.trading.util;
15
16 /**
17  * RWLock is a read-write lock; it allows multiple readers or a single
18  * writer; priority is given to writers
19  */

20 public class RWLock
21 {
22   private int m_numWaitingReaders = 0;
23   private int m_numWaitingWriters = 0;
24   private int m_refCount = 0;
25
26
27   public RWLock()
28   {
29   }
30
31
32   /** Acquire a write lock */
33   public synchronized void acquireWrite()
34   {
35     while (m_refCount != 0) {
36       m_numWaitingWriters++;
37       try {
38         wait();
39       }
40       catch (InterruptedException JavaDoc e) {
41       }
42       m_numWaitingWriters--;
43     }
44
45       // set m_refCount to indicate a write lock is active
46
m_refCount = -1;
47   }
48
49
50   /** Acquire a read lock */
51   public synchronized void acquireRead()
52   {
53       // give preference to waiting writers
54
while (m_refCount < 0 || m_numWaitingWriters > 0) {
55       m_numWaitingReaders++;
56       try {
57         wait();
58       }
59       catch (InterruptedException JavaDoc e) {
60       }
61       m_numWaitingReaders--;
62     }
63
64       // increment m_refCount to indicate a read lock is active
65
m_refCount++;
66   }
67
68
69   /** Release a lock */
70   public synchronized void release()
71   {
72     if (m_refCount > 0) // release a reader
73
m_refCount--;
74     else if (m_refCount == -1) // release a writer
75
m_refCount = 0;
76     else
77       throw new RuntimeException JavaDoc("refCount should not be 0");
78
79     notifyAll();
80   }
81 }
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
Popular Tags