// If the item is not in the cache, add it. // Evict an entry if the cache is full. public CachedItem GetItem(int iId) { CachedItem item = null; for (int i = 0; i < CachedItems.Length; i++) { if (CachedItems[i] != null) { if (CachedItems[i].iId == iId) { CachedItems[i].RecordAccess(); item = CachedItems[i]; break; } } } if (item == null) { int iItemToReplace = r.getRand(CachedItems.Length); EvictEntry(iItemToReplace); OnDiskItem temp = DiskItems.GetItem(iId); item = AddEntry(iItemToReplace, temp); iReplacedItems++; } return(item); }
CachedItem AddEntry(int iIndex, OnDiskItem item) { CachedItem itemToCache = new CachedItem(item); CachedItems[iIndex] = itemToCache; CachedItems[iIndex].RecordAccess(); iCachedCount++; return(itemToCache); }
public string GetUserData(int iId, bool fPin) { string strData; lock (this) { CachedItem item = GetItem(iId); strData = item.GetUserData(); if (fPin) { item.PinUserData(); } } return(strData); }
// I am not recording the access time when prepopulating the cache. public void InitCache(OnDiskData diskData, int iPercent) { DiskItems = diskData; int iDiskItemsCount = diskData.GetTotalItems(); int iCachedItemsCount = iDiskItemsCount * iPercent / 100; CachedItems = new CachedItem[iCachedItemsCount]; iReplacedItems = 0; int iAdded = 0; while (iAdded < iCachedItemsCount) { OnDiskItem temp = diskData.GetItem(r.getRand(iDiskItemsCount)); CachedItem item = new CachedItem(temp); CachedItems[iAdded] = item; iAdded++; } Console.WriteLine("Cached initialized: {0} entries, heap size is {1} bytes", iCachedItemsCount, GC.GetTotalMemory(true)); iCachedCount = iCachedItemsCount; }