DeveelDB  20151217
complete SQL database system, primarly developed for .NET/Mono frameworks
LockingQueue.cs
Go to the documentation of this file.
1 //
2 // Copyright 2010-2015 Deveel
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 using System;
18 using System.Collections.Generic;
19 using System.Linq;
20 using System.Threading;
21 
22 namespace Deveel.Data.Transactions {
23  public sealed class LockingQueue {
24  private readonly List<Lock> locks;
25 
26  internal LockingQueue(ILockable lockable) {
27  Lockable = lockable;
28  locks = new List<Lock>();
29  }
30 
31  public ILockable Lockable { get; private set; }
32 
33  public bool IsEmpty {
34  get {
35  lock (this) {
36  return !locks.Any();
37  }
38  }
39  }
40 
41  public void Acquire(Lock @lock) {
42  lock (this) {
43  locks.Add(@lock);
44  }
45  }
46 
47  public void Release(Lock @lock) {
48  lock (this) {
49  locks.Remove(@lock);
50  Lockable.Released(@lock);
51  Monitor.PulseAll(this);
52  }
53  }
54 
55  internal void CheckAccess(Lock @lock) {
56  lock (this) {
57  // Error checking. The queue must contain the Lock.
58  if (!locks.Contains(@lock))
59  throw new InvalidOperationException("Queue does not contain the given Lock");
60 
61  // If 'READ'
62  bool blocked;
63  int index;
64  if (@lock.AccessType == AccessType.Read) {
65  do {
66  blocked = false;
67 
68  index = locks.IndexOf(@lock);
69 
70  int i;
71  for (i = index - 1; i >= 0 && !blocked; --i) {
72  var testLock = locks[i];
73  if (testLock.AccessType == AccessType.Write)
74  blocked = true;
75  }
76 
77  if (blocked) {
78  Monitor.Wait(this);
79  }
80  } while (blocked);
81  } else {
82  do {
83  blocked = false;
84 
85  index = locks.IndexOf(@lock);
86 
87  if (index != 0) {
88  blocked = true;
89 
90  Monitor.Wait(this);
91  }
92 
93  } while (blocked);
94  }
95 
96  // Notify the Lock table that we've got a lock on it.
97  // TODO: Lock.Table.LockAcquired(Lock);
98  }
99  }
100  }
101 }