File: QueryCacheManager.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (460 lines) | stat: -rw-r--r-- 16,861 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//------------------------------------------------------------------------------
// <copyright file="QueryCacheManager.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner  Microsoft
// @backupOwner Microsoft
//------------------------------------------------------------------------------

namespace System.Data.Common.QueryCache
{
    using System;
    using System.Collections.Generic;
    using System.Data.EntityClient;
    using System.Data.Metadata.Edm;
    using System.Data.Objects.Internal;
    using System.Diagnostics;
    using System.Threading;
    using System.Data.Common.Internal.Materialization;
    using System.Data.Entity.Util;

    /// <summary>
    /// Provides Query Execution Plan Caching Service 
    /// </summary>
    /// <remarks>
    /// Thread safe.
    /// Dispose <b>must</b> be called as there is no finalizer for this class
    /// </remarks>
    internal class QueryCacheManager : IDisposable
    {
        #region Constants/Default values for configuration parameters

        /// <summary>
        /// Default high mark for starting sweeping process
        /// default value: 80% of MaxNumberOfEntries
        /// </summary>
        const float DefaultHighMarkPercentageFactor = 0.8f; // 80% of MaxLimit

        /// <summary>
        /// Recycler timer period
        /// </summary>
        const int DefaultRecyclerPeriodInMilliseconds = 60 * 1000;

        #endregion

        #region Fields
        
        /// <summary>
        /// cache lock object
        /// </summary>
        private readonly object _cacheDataLock = new object();

        /// <summary>
        /// cache data
        /// </summary>
        private readonly Dictionary<QueryCacheKey, QueryCacheEntry> _cacheData = new Dictionary<QueryCacheKey, QueryCacheEntry>(32);

        /// <summary>
        /// soft maximum number of entries in the cache
        /// </summary>
        private readonly int _maxNumberOfEntries;

        /// <summary>
        /// high mark of the number of entries to trigger the sweeping process
        /// </summary>
        private readonly int _sweepingTriggerHighMark;

        /// <summary>
        /// Eviction timer 
        /// </summary>
        private readonly EvictionTimer _evictionTimer;

        #endregion
        
        #region Construction and Initialization

        /// <summary>
        /// Constructs a new Query Cache Manager instance, with default values for all 'configurable' parameters.
        /// </summary>
        /// <returns>A new instance of <see cref="QueryCacheManager"/> configured with default entry count, load factor and recycle period</returns>
        internal static QueryCacheManager Create()
        {
            return new QueryCacheManager(AppSettings.QueryCacheSize, DefaultHighMarkPercentageFactor, DefaultRecyclerPeriodInMilliseconds);
        }

        /// <summary>
        /// Cache Constructor
        /// </summary>
        /// <param name="maximumSize">
        ///   Maximum number of entries that the cache should contain.
        /// </param>
        /// <param name="loadFactor">
        ///   The number of entries that must be present, as a percentage, before entries should be removed
        ///   according to the eviction policy.
        ///   Must be greater than 0 and less than or equal to 1.0
        /// </param>
        /// <param name="recycleMillis">
        ///   The interval, in milliseconds, at which the number of entries will be compared to the load factor
        ///   and eviction carried out if necessary.
        /// </param>
        private QueryCacheManager(int maximumSize, float loadFactor, int recycleMillis)
        {
            Debug.Assert(maximumSize > 0, "Maximum size must be greater than zero");
            Debug.Assert(loadFactor > 0 && loadFactor <= 1, "Load factor must be greater than 0.0 and less than or equal to 1.0");
            Debug.Assert(recycleMillis >= 0, "Recycle period in milliseconds must not be negative");

            //
            // Load hardcoded defaults
            //
            this._maxNumberOfEntries = maximumSize;

            //
            // set sweeping high mark trigger value
            //
            this._sweepingTriggerHighMark = (int)(_maxNumberOfEntries * loadFactor);

            //
            // Initialize Recycler
            //
            this._evictionTimer = new EvictionTimer(this, recycleMillis);           
        }
                
        #endregion

        #region 'External' interface
        /// <summary>
        /// Adds new entry to the cache using "abstract" cache context and
        /// value; returns an existing entry if the key is already in the
        /// dictionary.
        /// </summary>
        /// <param name="inQueryCacheEntry"></param>
        /// <param name="outQueryCacheEntry">
        /// The existing entry in the dicitionary if already there;
        /// inQueryCacheEntry if none was found and inQueryCacheEntry
        /// was added instead.
        /// </param>
        /// <returns>true if the output entry was already found; false if it had to be added.</returns>
        internal bool TryLookupAndAdd(QueryCacheEntry inQueryCacheEntry, out QueryCacheEntry outQueryCacheEntry)
        {
            Debug.Assert(null != inQueryCacheEntry, "qEntry must not be null");

            outQueryCacheEntry = null;

            lock (_cacheDataLock)
            {
                if (!_cacheData.TryGetValue(inQueryCacheEntry.QueryCacheKey, out outQueryCacheEntry))
                {
                    //
                    // add entry to cache data
                    //
                    _cacheData.Add(inQueryCacheEntry.QueryCacheKey, inQueryCacheEntry);
                    if (_cacheData.Count > _sweepingTriggerHighMark)
                    {
                        _evictionTimer.Start();
                    }

                    return false;
                }
                else
                {
                    outQueryCacheEntry.QueryCacheKey.UpdateHit();

                    return true;
                }
            }
        }

        /// <summary>
        /// Lookup service for a cached value.
        /// </summary>
        internal bool TryCacheLookup<TK, TE>(TK key, out TE value)
            where TK : QueryCacheKey
        {
            Debug.Assert(null != key, "key must not be null");

            value = default(TE);

            //
            // invoke internal lookup
            //
            QueryCacheEntry qEntry = null;
            bool bHit = TryInternalCacheLookup(key, out qEntry);

            //
            // if it is a hit, 'extract' the entry strong type cache value
            //
            if (bHit)
            {
                value = (TE)qEntry.GetTarget();
            }

            return bHit;
        }

        /// <summary>
        /// Clears the Cache
        /// </summary>
        internal void Clear()
        {
            lock (_cacheDataLock)
            {
                _cacheData.Clear();
            }
        }
        #endregion

        #region Private Members
        
        /// <summary>
        /// lookup service
        /// </summary>
        /// <param name="queryCacheKey"></param>
        /// <param name="queryCacheEntry"></param>
        /// <returns>true if cache hit, false if cache miss</returns>
        private bool TryInternalCacheLookup( QueryCacheKey queryCacheKey, out QueryCacheEntry queryCacheEntry )
        {
            Debug.Assert(null != queryCacheKey, "queryCacheKey must not be null");

            queryCacheEntry = null;

            bool bHit = false;

            //
            // lock the cache for the minimal possible period
            //
            lock (_cacheDataLock)
            {
                bHit = _cacheData.TryGetValue(queryCacheKey, out queryCacheEntry);
            }

            //
            // if cache hit
            //
            if (bHit)
            {
                //
                // update hit mark in cache key
                //
                queryCacheEntry.QueryCacheKey.UpdateHit();
            }
            
            return bHit;
        }


        /// <summary>
        /// Recycler handler. This method is called directly by the eviction timer.
        /// It should take no action beyond invoking the <see cref="SweepCache"/> method on the 
        /// cache manager instance passed as <paramref name="state"/>.
        /// </summary>
        /// <param name="state">The cache manager instance on which the 'recycle' handler should be invoked</param>
        private static void CacheRecyclerHandler(object state)
        {
            ((QueryCacheManager)state).SweepCache();
        }

        /// <summary>
        /// Aging factor
        /// </summary>
        private static readonly int[] _agingFactor = {1,1,2,4,8,16};
        private static readonly int AgingMaxIndex = _agingFactor.Length - 1;

        /// <summary>
        /// Sweeps the cache removing old unused entries.
        /// This method implements the query cache eviction policy.
        /// </summary>
        private void SweepCache()
        {
            if (!this._evictionTimer.Suspend())
            {
                // Return of false from .Suspend means that the manager and timer have been disposed.
                return;
            }

            bool disabledEviction = false;
            lock (_cacheDataLock)
            {
                //
                // recycle only if entries exceeds the high mark factor
                //
                if (_cacheData.Count > _sweepingTriggerHighMark)
                {
                    //
                    // sweep the cache
                    //
                    uint evictedEntriesCount = 0;
                    List<QueryCacheKey> cacheKeys = new List<QueryCacheKey>(_cacheData.Count);
                    cacheKeys.AddRange(_cacheData.Keys);
                    for (int i = 0; i < cacheKeys.Count; i++)
                    {
                        //
                        // if entry was not used in the last time window, then evict the entry
                        //
                        if (0 == cacheKeys[i].HitCount)
                        {
                            _cacheData.Remove(cacheKeys[i]);
                            evictedEntriesCount++;
                        }
                        //
                        // otherwise, age the entry in a progressive scheme
                        //
                        else
                        {
                            int agingIndex = unchecked(cacheKeys[i].AgingIndex + 1);
                            if (agingIndex > AgingMaxIndex)
                            {
                                agingIndex = AgingMaxIndex;
                            }
                            cacheKeys[i].AgingIndex = agingIndex;
                            cacheKeys[i].HitCount = cacheKeys[i].HitCount >> _agingFactor[agingIndex];
                        }
                    }
                }
                else
                {
                    _evictionTimer.Stop();
                    disabledEviction = true;
                }
            }

            if (!disabledEviction)
            {
                this._evictionTimer.Resume();
            }
        }
              
        #endregion

        #region IDisposable Members
        
        /// <summary>
        /// Dispose instance
        /// </summary>
        /// <remarks>Dispose <b>must</b> be called as there are no finalizers for this class</remarks>
        public void Dispose()
        {
            // Technically, calling GC.SuppressFinalize is not required because the class does not
            // have a finalizer, but it does no harm, protects against the case where a finalizer is added
            // in the future, and prevents an FxCop warning.
            GC.SuppressFinalize(this);
            if (this._evictionTimer.Stop())
            {
                this.Clear();
            }
        }

        #endregion

        /// <summary>
        /// Periodically invokes cache cleanup logic on a specified <see cref="QueryCacheManager"/> instance,
        /// and allows this periodic callback to be suspended, resumed or stopped in a thread-safe way.
        /// </summary>
        private sealed class EvictionTimer
        {
            /// <summary>Used to control multi-threaded accesses to this instance</summary>
            private readonly object _sync = new object();

            /// <summary>The required interval between invocations of the cache cleanup logic</summary>
            private readonly int _period;

            /// <summary>The underlying QueryCacheManger that the callback will act on</summary>
            private readonly QueryCacheManager _cacheManager;

            /// <summary>The underlying <see cref="Timer"/> that implements the periodic callback</summary>
            private Timer _timer;

            internal EvictionTimer(QueryCacheManager cacheManager, int recyclePeriod)
            {
                this._cacheManager = cacheManager;
                this._period = recyclePeriod;
            }

            internal void Start()
            {
                lock (_sync)
                {
                    if (_timer == null)
                    {
                        this._timer = new Timer(QueryCacheManager.CacheRecyclerHandler, _cacheManager, _period, _period);
                    }
                }
            }
                        
            /// <summary>
            /// Permanently stops the eviction timer.
            /// It will no longer generate periodic callbacks and further calls to <see cref="Suspend"/>, <see cref="Resume"/>, or <see cref="Stop"/>,
            /// though thread-safe, will have no effect.
            /// </summary>
            /// <returns>
            ///   If this eviction timer has already been stopped (using the <see cref="Stop"/> method), returns <c>false</c>;
            ///   otherwise, returns <c>true</c> to indicate that the call successfully stopped and cleaned up the underlying timer instance.
            /// </returns>
            /// <remarks>
            ///   Thread safe. May be called regardless of the current state of the eviction timer.
            ///   Once stopped, an eviction timer cannot be restarted with the <see cref="Resume"/> method.
            /// </remarks>
            internal bool Stop()
            {
                lock (_sync)
                {
                    if (this._timer != null)
                    {
                        this._timer.Dispose();
                        this._timer = null;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            /// <summary>
            /// Pauses the operation of the eviction timer. 
            /// </summary>
            /// <returns>
            ///   If this eviction timer has already been stopped (using the <see cref="Stop"/> method), returns <c>false</c>;
            ///   otherwise, returns <c>true</c> to indicate that the call successfully suspended the inderlying <see cref="Timer"/>
            ///   and no further periodic callbacks will be generated until the <see cref="Resume"/> method is called.
            /// </returns>
            /// <remarks>
            ///   Thread-safe. May be called regardless of the current state of the eviction timer.
            ///   Once suspended, an eviction timer may be resumed or stopped.
            /// </remarks>
            internal bool Suspend()
            {
                lock (_sync)
                {
                    if (this._timer != null)
                    {
                        this._timer.Change(Timeout.Infinite, Timeout.Infinite);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            /// <summary>
            /// Causes this eviction timer to generate periodic callbacks, provided it has not been permanently stopped (using the <see cref="Stop"/> method).
            /// </summary>
            /// <remarks>
            ///   Thread-safe. May be called regardless of the current state of the eviction timer.
            /// </remarks>
            internal void Resume()
            {
                lock (_sync)
                {
                    if (this._timer != null)
                    {
                        this._timer.Change(this._period, this._period);
                    }
                }
            }
        }
    }
}