source: trunk/sources/HeuristicLab.Hive.Server.ADODataAccess/CachedDataAdapter.cs @ 1134

Last change on this file since 1134 was 1134, checked in by svonolfe, 12 years ago

Further improved locking mechanism (avoid race conditions, performance) (#372)

File size: 6.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Text;
26using HeuristicLab.Hive.Contracts.BusinessObjects;
27using System.Data;
28using System.Threading;
29
30namespace HeuristicLab.Hive.Server.ADODataAccess {
31  abstract class CachedDataAdapter<AdapterT, ObjT, RowT, CacheT> :
32    DataAdapterBase<AdapterT, ObjT, RowT>,
33    ICachedDataAdapter
34    where CacheT : System.Data.TypedTableBase<RowT>, new()
35    where AdapterT : new()
36    where RowT : System.Data.DataRow
37    where ObjT : IHiveObject, new() {
38    protected static CacheT cache =
39      new CacheT();
40
41    private static bool cacheFilled = false;
42
43    private static ReaderWriterLock cacheLock =
44      new ReaderWriterLock();
45
46    protected DataTable dataTable =
47      new DataTable();
48
49    protected ICollection<ICachedDataAdapter> parentAdapters =
50      new List<ICachedDataAdapter>();
51
52    protected CachedDataAdapter() {
53      cacheLock.AcquireWriterLock(Timeout.Infinite);
54
55      if (!cacheFilled) {
56        FillCache();
57        cacheFilled = true;
58      }
59
60      cacheLock.ReleaseWriterLock();
61
62      ServiceLocator.GetTransactionManager().OnUpdate +=
63        new EventHandler(CachedDataAdapter_OnUpdate);
64    }
65
66    protected virtual RowT FindSingleRow(Selector dbSelector,
67      Selector cacheSelector) {
68      cacheLock.AcquireReaderLock(Timeout.Infinite);
69     
70      RowT row =
71         FindSingleRow(cacheSelector);
72
73      //not in cache
74      if (row == null) {
75        row =
76          FindSingleRow(dbSelector);
77      }
78
79      cacheLock.ReleaseReaderLock();
80
81      return row;
82    }
83
84    protected virtual IEnumerable<RowT> FindMultipleRows(Selector dbSelector,
85        Selector cacheSelector) {
86      cacheLock.AcquireReaderLock(Timeout.Infinite);
87
88      IList<RowT> result =
89         new List<RowT>(cacheSelector());
90
91      IEnumerable<RowT> result2 =
92          dbSelector();
93
94      foreach (RowT row in result2) {
95        if (!IsCached(row)) {
96          result.Add(row);
97        }
98      }
99
100      cacheLock.ReleaseReaderLock();
101
102      return result;
103    }
104
105    protected virtual ObjT FindSingle(Selector dbSelector,
106      Selector cacheSelector) {
107      RowT row = FindSingleRow(dbSelector, cacheSelector);
108
109      if (row != null) {
110        ObjT obj = new ObjT();
111        obj = Convert(row, obj);
112       
113        return obj;
114      } else {
115        return default(ObjT);
116      }
117    }
118
119    protected virtual ICollection<ObjT> FindMultiple(Selector dbSelector,
120      Selector cacheSelector) {
121      cacheLock.AcquireReaderLock(Timeout.Infinite);
122
123      ICollection<ObjT> result =
124        FindMultiple(cacheSelector);
125
126      ICollection<ObjT> resultDb =
127        FindMultiple(dbSelector);
128
129      cacheLock.ReleaseReaderLock();
130
131      foreach (ObjT obj in resultDb) {
132        if (!result.Contains(obj))
133          result.Add(obj);
134      }
135
136      return result;
137    }
138
139    protected abstract RowT InsertNewRowInCache(ObjT obj);
140
141    protected abstract void FillCache();
142
143    public abstract void SyncWithDb();
144
145    protected abstract bool PutInCache(ObjT obj);
146
147    protected abstract RowT FindCachedById(long id);
148
149    void CachedDataAdapter_OnUpdate(object sender, EventArgs e) {
150      foreach (ICachedDataAdapter parent in this.parentAdapters) {
151        parent.SyncWithDb();
152      }
153
154      this.SyncWithDb();
155    }
156
157    protected virtual bool IsCached(RowT row) {
158      if (row == null)
159        return false;
160      else
161        return FindCachedById((long)row[row.Table.PrimaryKey[0]]) != null;
162    }
163
164    protected override RowT GetRowById(long id) {
165      RowT row =
166        FindCachedById(id);
167
168      if (row == null)
169        row = FindSingleRow(
170          delegate() {
171            return FindById(id);
172          });
173
174      return row;
175    }
176
177    private void AddToCache(RowT row) {
178      cacheLock.AcquireWriterLock(Timeout.Infinite);
179
180      cache.ImportRow(row);
181      row.Table.Rows.Remove(row);
182
183      cacheLock.ReleaseWriterLock();
184    }
185
186    private RowT AddToCache(ObjT obj) {
187      cacheLock.AcquireWriterLock(Timeout.Infinite);
188
189      RowT row =  InsertNewRowInCache(obj);
190
191      cacheLock.ReleaseWriterLock();
192
193      return row;
194    }
195
196    private void RemoveRowFromCache(RowT row) {
197      cacheLock.AcquireWriterLock(Timeout.Infinite);
198
199      dataTable.ImportRow(row);
200      cache.Rows.Remove(row);
201
202      cacheLock.ReleaseWriterLock();
203
204      UpdateRow(row);
205    }
206
207    public override void Update(ObjT obj) {
208      if (obj != null) {
209        RowT row =
210          GetRowById(obj.Id);
211
212        if (row == null) {
213          if (PutInCache(obj)) {
214            row = AddToCache(obj);
215          } else {
216            row = InsertNewRow(obj);
217          }
218
219          UpdateRow(row);
220        }
221
222        obj.Id = (long)row[row.Table.PrimaryKey[0]];
223        LockRow(obj.Id);
224
225        ConvertObj(obj, row);
226
227        if (!IsCached(row))
228          UpdateRow(row);
229
230        if (IsCached(row) &&
231            !PutInCache(obj)) {         
232          RemoveRowFromCache(row);
233        } else if (!IsCached(row) &&
234          PutInCache(obj)) {
235          AddToCache(row);
236        }
237
238        UnlockRow(obj.Id);
239      }
240    }
241  }
242}
243
Note: See TracBrowser for help on using the repository browser.