????????
?????????storm?????????е?TimeCacheMap??????????Ч??????????????
??????????????????????????????????????????????????????????????????????????ж???????????????????????????????????????????O(n)?????????С???????????????????????????????????????????????????????????????????д?????
????Storm???????????Ч????仺??????TimeCacheMap?????????????????????????????????????????????????????????????????????????д??????????O(1)??
??????????
????TimeCacheMap??????????????洢?????С?????????????????????и???????????????????????Щ????????????????????????????????? ???е??????????????????????????????????裬???????????????????????????????????????10s???????????10??????????????????????????????????????????????????·????????
???????????????????????????????????£?
????private LinkedList<Dictionary<K?? V>> buckets;
????private readonly object Obj = new object();
????private static readonly int NumBuckets = 3;
????private Thread cleaner;
?????????????k??v??????????????????????Dictionary???????????????????????洢??????Obj??????????NumBuckets???????????cleaner??????????
??????????????????????????????????buckets???????????????????飬???????????30??????????3??????????????????????????????????С?
????????????????????????????????????????????????????????к??????????????????????????????????????
????????????2??????????????????????????????????????????????30???????????????????????????????????90????????????????????????????? ???????????30????????????????????????????????????10??????????£?
?????????1?????????????????????????????10??????????????????????????20??????????????30?????????????????????1????9???????????????????????????????????
??????????????????????????????????????????????????????????Щ???????????????????????? ?????????15???????????1????????????????30????????????????????????????
??????????????14???????????????????30??+14??????????
??????????????????????15????????????????????????????泤?????????????
????expirationSecs * (1 + 1 / (numBuckets-1))
????????????????30?????????????
????30*(1+1/(3-1))=30*(1+0.5)=45
???????????????Χ???expirationSecs??expirationSecs * (1 + 1 / (numBuckets-1))???
???????????
???????????????????????????????????У???????????????????
public TimeCacheMap(int expirationSecs?? int numBuckets?? ExpiredCallBack ex)
{
if (numBuckets < 2)
throw new ArgumentException("numBuckets must be >=2");
this.buckets = new LinkedList<Dictionary<K?? V>>();
for (int i = 0; i < numBuckets; i++)
buckets.AddFirst(new Dictionary<K?? V>());
var expirationMillis = expirationSecs * 1000;
var sleepTime = expirationMillis / (numBuckets - 1);
cleaner = new Thread(() =>
{
while (true)
{
Dictionary<K?? V> dead = null;
Thread.Sleep(sleepTime);
lock (Obj)
{
dead = buckets.Last();
buckets.RemoveLast();
buckets.AddFirst(new Dictionary<K?? V>());
}
if (ex != null)
ex(dead);
}
});
cleaner.IsBackground = true;
cleaner.Start();
}