Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.DataAccess.ADOHelper/CachedDataAdapter.cs @ 1452

Last change on this file since 1452 was 1452, checked in by svonolfe, 15 years ago

Fixed small bug in DAL related to caching (#372)

File size: 6.8 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.Text;
25using System.Data;
26using System.Threading;
27using HeuristicLab.DataAccess.Interfaces;
28
29namespace HeuristicLab.DataAccess.ADOHelper {
30  public abstract class CachedDataAdapter<AdapterT, ObjT, RowT, CacheT> :
31    DataAdapterBase<AdapterT, ObjT, RowT>,
32    ICachedDataAdapter
33    where CacheT : System.Data.TypedTableBase<RowT>, new()
34    where AdapterT : new()
35    where RowT : System.Data.DataRow
36    where ObjT : IPersistableObject, new() {
37    protected static CacheT cache =
38      new CacheT();
39
40    private static bool cacheFilled = false;
41
42    private static ReaderWriterLockSlim cacheLock =
43      new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
44
45    protected ICollection<ICachedDataAdapter> parentAdapters =
46      new List<ICachedDataAdapter>();
47
48    protected CachedDataAdapter(IDBSynchronizer synchronizer) {
49      cacheLock.EnterWriteLock();
50
51      if (!cacheFilled) {
52        FillCache();
53        cacheFilled = true;
54      }
55
56      cacheLock.ExitWriteLock();
57
58      synchronizer.OnUpdate +=
59        new EventHandler(CachedDataAdapter_OnUpdate);
60    }
61
62    protected virtual RowT FindSingleRow(Selector dbSelector,
63      Selector cacheSelector) {
64      cacheLock.EnterReadLock();
65     
66      RowT row =
67         FindSingleRow(cacheSelector);
68
69      //not in cache
70      if (row == null) {
71        row =
72          FindSingleRow(dbSelector);
73      }
74
75      cacheLock.ExitReadLock();
76
77      return row;
78    }
79
80    protected virtual IEnumerable<RowT> FindMultipleRows(Selector dbSelector,
81        Selector cacheSelector) {
82      cacheLock.EnterReadLock();
83
84      IList<RowT> result =
85         new List<RowT>(cacheSelector());
86
87      IEnumerable<RowT> result2 =
88          dbSelector();
89
90      foreach (RowT row in result2) {
91        if (!IsCached(row)) {
92          result.Add(row);
93        }
94      }
95
96      cacheLock.ExitReadLock();
97
98      return result;
99    }
100
101    protected virtual ObjT FindSingle(Selector dbSelector,
102      Selector cacheSelector) {
103      ObjT obj = default(ObjT);
104
105      cacheLock.EnterReadLock();
106
107      RowT row = FindSingleRow(dbSelector, cacheSelector);
108
109      if (row != null) {
110        obj = new ObjT();
111        obj = Convert(row, obj);
112      }
113
114      cacheLock.ExitReadLock();
115
116      return obj;
117    }
118
119    protected virtual ICollection<ObjT> FindMultiple(Selector dbSelector,
120      Selector cacheSelector) {
121      cacheLock.EnterReadLock();
122
123      ICollection<ObjT> result =
124        FindMultiple(cacheSelector);
125
126      ICollection<ObjT> resultDb =
127        FindMultiple(dbSelector);
128
129      cacheLock.ExitReadLock();
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    protected abstract void SynchronizeWithDb();
144
145    protected abstract bool PutInCache(ObjT obj);
146
147    protected abstract RowT FindCachedById(Guid id);
148
149    public void SyncWithDb() {
150      foreach (ICachedDataAdapter parent in this.parentAdapters) {       
151        parent.SyncWithDb();
152      }
153
154      cacheLock.EnterReadLock();
155
156      this.SynchronizeWithDb();
157
158      cacheLock.ExitReadLock();
159    }
160
161    void CachedDataAdapter_OnUpdate(object sender, EventArgs e) {
162      this.SyncWithDb();
163    }
164
165    protected virtual bool IsCached(RowT row) {
166      if (row == null)
167        return false;
168      else {
169        cacheLock.EnterReadLock();
170
171        bool cached = FindCachedById((Guid)row[row.Table.PrimaryKey[0]]) != null;
172
173        cacheLock.ExitReadLock();
174
175        return cached;
176      }
177    }
178
179    protected override RowT GetRowById(Guid id) {
180      cacheLock.EnterReadLock();
181
182      RowT row =
183        FindCachedById(id);
184
185      //not in cache
186      if (row == null)
187        row = FindSingleRow(
188          delegate() {
189            return FindById(id);
190          });
191
192      cacheLock.ExitReadLock();
193
194      return row;
195    }
196
197    private void AddToCache(RowT row) {
198      cacheLock.EnterWriteLock();
199
200      cache.ImportRow(row);
201      row.Table.Rows.Remove(row);
202
203      cacheLock.ExitWriteLock();
204    }
205
206    private RowT AddToCache(ObjT obj) {
207      cacheLock.EnterWriteLock();
208
209      RowT row =  InsertNewRowInCache(obj);
210
211      cacheLock.ExitWriteLock();
212
213      return row;
214    }
215
216    private void RemoveRowFromCache(RowT row) {
217      cacheLock.EnterWriteLock();
218
219      UpdateRow(row);
220
221      row.Table.Rows.Remove(row);     
222
223      cacheLock.ExitWriteLock();
224    }
225
226    public override ObjT GetById(Guid id) {
227      return FindSingle(
228        delegate() {
229          return FindById(id);
230        },
231        delegate() {
232          List<RowT> found = 
233            new List<RowT>();
234          found.Add(
235              FindCachedById(id));
236          return found;
237        });
238    }
239
240    public override void Update(ObjT obj) {
241      if (obj != null) {
242        RowT row = null;
243        Guid locked = Guid.Empty;
244
245        if (obj.Id != Guid.Empty) {
246          LockRow(obj.Id);
247          locked = obj.Id;
248
249          row = GetRowById(obj.Id);
250        } else {
251          obj.Id = Guid.NewGuid();
252        }
253
254        if (row == null) {
255          if (PutInCache(obj)) {
256            row = AddToCache(obj);
257          } else {
258            row = InsertNewRow(obj);
259            UpdateRow(row);
260          }
261        }
262
263        if (locked == Guid.Empty)
264        {
265          LockRow(obj.Id);
266          locked = obj.Id;
267        }
268
269        ConvertObj(obj, row);
270
271        if (!IsCached(row))
272          UpdateRow(row);
273
274        if (IsCached(row) &&
275            !PutInCache(obj)) {         
276          RemoveRowFromCache(row);
277        } else if (!IsCached(row) &&
278          PutInCache(obj)) {
279          AddToCache(row);
280        }
281
282        UnlockRow(locked);
283      }
284    }
285  }
286}
287
Note: See TracBrowser for help on using the repository browser.