/// <summary>
        /// Creates a new <see cref="ChunkCache"/> with the given chunk capacity.
        /// </summary>
        /// <param name="cacheSize">The capacity of the LRU-portion of the cache.</param>
        public ChunkCache (int cacheSize)
        {
            _cache = new LRUCache<ChunkKey, ChunkRef>(cacheSize);
            _dirty = new Dictionary<ChunkKey, ChunkRef>();

            _cache.RemoveCacheValue += EvictionHandler;
        }
        static void lru_OnRemoveItem(LRUCache<int, Image<Gray, byte>> sender, KeyValuePair<int, Image<Gray, byte>> item, bool userRequested)
        {
            sender.Oldest.Value.Dispose();
            GC.Collect();

            Console.WriteLine("Kicked out!");
        }
        static void Main(string[] args)
        {
            LRUCache<int, int> lruCache = new LRUCache<int, int>(5);

            Console.WriteLine(lruCache.Size());

            lruCache.Insert(0, 10);
            lruCache.Insert(1, 20);
            lruCache.Insert(2, 30);
            lruCache.Insert(3, 40);
            lruCache.Insert(4, 50);

            Console.WriteLine(lruCache.Size());
            Console.WriteLine(lruCache.CacheFeed());

            lruCache.GetItem(0);
            lruCache.GetItem(1);
            lruCache.GetItem(2);

            Console.WriteLine(lruCache.Size());
            Console.WriteLine(lruCache.CacheFeed());

            lruCache.Insert(5, 60);
            lruCache.Insert(6, 70);
            lruCache.Insert(7, 80);
            lruCache.Insert(8, 90);
            lruCache.Insert(9, 100);

            Console.WriteLine(lruCache.Size());
            Console.WriteLine(lruCache.CacheFeed());
        }
Example #4
0
        public void BasicTest()
        {
            var cache = new LRUCache<int, int>(2);
            var invocationCount = 0;

            Func<int, int> factory = k =>
            {
                invocationCount++;

                // extremely CPU intensive operation
                return k*2;
            };

            cache.Get(1, factory); // a: factory()
            cache.Get(2, factory); // b: factory()
            cache.Get(1, factory); // c: cached (a)
            cache.Get(2, factory); // d: cached (b)
            cache.Get(3, factory); // e: factory(); discard [1,2] (c)
            cache.Get(1, factory); // f: factory(); discard [2,4] (d)

            // we should have had 2 cached results
            // and 4 factory invocations
            Assert.AreEqual(4, invocationCount); // (a,b,e,f)

            // should only have 2 items in cache
            Assert.AreEqual(2, cache.Count); // (e,f)

            // we should have the keys/values enumerated in order of most -> least recently used
            CollectionAssert.AreEqual(new[]
            {
                new KeyValuePair<int, int>(1, 2), // (f)
                new KeyValuePair<int, int>(3, 6), // (e)
            }, cache);
        }
Example #5
0
 public void Test(int capacity, string operationsString, string expectedOutputString)
 {
     var cache = new LRUCache(capacity);
     var output = new StringBuilder();
     foreach (var operationString in operationsString.Split(';'))
     {
         int key;
         int value;
         switch (operationString[0])
         {
             case 'g':
                 key = int.Parse(operationString.Substring(1));
                 if (output.Length > 0)
                 {
                     output.Append(";");
                 }
                 output.Append(cache.Get(key).ToString(CultureInfo.InvariantCulture));
                 break;
             case 's':
                 var indexOfComma = operationString.IndexOf(',');
                 key = int.Parse(operationString.Substring(1, indexOfComma - 1));
                 value = int.Parse(operationString.Substring(indexOfComma + 1));
                 cache.Set(key, value);
                 break;
             default:
                 throw new Exception(string.Format("Unkown operation: {0}", operationString));
         }
     }
     
     Assert.AreEqual(expectedOutputString, output.ToString());
 }
Example #6
0
 public static void RunTests()
 {
     LRUCache cache = new LRUCache(5);
     cache.Insert("A", 11);
     cache.Insert("B", 22);
     cache.Insert("C", 33);
     int price = 0;
     Console.Write(cache.Lookup("A", out price) + " ");
     Console.WriteLine(price);
     Console.Write(cache.Lookup("B", out price) + " ");
     Console.WriteLine(price);
     Console.Write(cache.Lookup("C", out price) + " ");
     Console.WriteLine(price);
     cache.Insert("D", 44);
     cache.Insert("E", 55);
     cache.Insert("F", 66);
     Console.Write(cache.Lookup("F", out price) + " ");
     Console.WriteLine(price);
     Console.WriteLine(cache.Lookup("A", out price));
     Console.Write(cache.Lookup("B", out price) + " ");
     Console.WriteLine(price);
     cache.Remove("F");
     Console.WriteLine(cache.Lookup("F", out price));
     cache.Update("B", 23);
     Console.Write(cache.Lookup("B", out price) + " ");
     Console.WriteLine(price);
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="capacity">The maximim capacity for the cache</param>
        /// <param name="inner">The IKeyResolver to wrap</param>
        public CachingKeyResolver( int capacity, IKeyResolver inner )
        {
            if ( inner == null )
                throw new ArgumentNullException( "inner" );

            _cache = new LRUCache<string, IKey>( capacity );
            _inner = inner;
        }
Example #8
0
        static PhotoManager()
        {
            string Documents = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
            PhotosDir = Path.Combine (Path.GetDirectoryName (Documents), "Library", "Photos");
            if (!Directory.Exists (PhotosDir))
                Directory.CreateDirectory (PhotosDir);

            ThumbnailCache = new LRUCache<string, UIImage> (12);
        }
Example #9
0
 /// <summary>
 /// A simple tester to see if the LRU cache is working correctly
 /// </summary>
 public static void Main()
 {
     LRUCache<int> intCache = new LRUCache<int>() { 1, 2, 3, 4 };
     intCache.Add(5);
     intCache.Remove(2);
     intCache.Add(6);
     Console.WriteLine(intCache);
     Console.ReadLine();
 }
Example #10
0
        public void ForceLockRecursionException()
        {
            var cache = new LRUCache<int, int>(1);

            cache.Get(0, k => k);

            // write during a read
            foreach (var item in cache)
                Assert.Throws<LockRecursionException>(() => cache.Get(1, k => k));
        }
Example #11
0
        public void LRUCacheTest()
        {
            // create the LRU cache.
            LRUCache<int, int> cache = new LRUCache<int, int>(5);

            // add some stuff.
            cache.Add(0, 1);
            cache.Add(1, 1);
            cache.Add(2, 1);
            cache.Add(3, 1);
            cache.Add(4, 1);
            cache.Add(5, 1);
            cache.Add(6, 1);

            int value;
            Assert.IsTrue(cache.TryPeek(6, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(5, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(4, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(2, out value));
            Assert.AreEqual(1, value);

            Assert.IsFalse(cache.TryPeek(1, out value)); // not in cache anymore.
            Assert.IsFalse(cache.TryPeek(0, out value)); // not in cache anymore.

            // 'use' 2 and 3.
            Assert.IsTrue(cache.TryGet(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryGet(2, out value));
            Assert.AreEqual(1, value);

            // add 7 and 8.
            cache.Add(7, 1);
            cache.Add(8, 1);

            // cache should now contain 2, 3, 7, 8, 6
            Assert.IsTrue(cache.TryPeek(2, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(3, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(7, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(8, out value));
            Assert.AreEqual(1, value);
            Assert.IsTrue(cache.TryPeek(6, out value));
            Assert.AreEqual(1, value);

            Assert.IsFalse(cache.TryPeek(4, out value)); // not in cache anymore.
            Assert.IsFalse(cache.TryPeek(5, out value)); // not in cache anymore.
        }
Example #12
0
        public void Remove()
        {
            var dico = new LRUCache<string, int>();

            dico.Set("the answer", 42);
            Assert.AreEqual(42, dico.RawGet("the answer"));
            Assert.AreEqual(1, dico.Count);
            Assert.AreEqual(1, dico.NbUpdate);

            dico.Remove("the answer");
            Assert.AreEqual(0, dico.RawGet("the answer"));
            Assert.AreEqual(0, dico.Count);
            Assert.AreEqual(1, dico.NbUpdate);
        }
 public static void Init(string[] args)
 {
     LRUCache obj = new LRUCache(5);
     obj.Set(1, 1);
     Console.WriteLine(obj.Get(1));
     obj.Set(2, 2);
     obj.Set(3, 3);
     obj.Set(4, 4);
     obj.Set(5, 5);
     obj.Set(6, 6);
     Console.WriteLine(obj.Get(1));
     Console.WriteLine(obj.Get(3));
     Console.WriteLine(obj.Get(6));
 }
Example #14
0
        public void TestRetrieveItemThatDoesntExist()
        {
            var cache = new LRUCache<UUID, String>(MAX_CACHE_SIZE);
            String testData = "Test Data";
            UUID id = UUID.Random();

            cache.Add(id, testData);

            String entry = null;
            Assert.AreEqual(1, cache.Size);
            Assert.AreEqual(1, cache.Count);
            Assert.IsFalse(cache.TryGetValue(UUID.Random(), out entry));
            Assert.IsNull(entry);
        }
Example #15
0
        public void TestSimpleCacheAndRetrieval()
        {
            var cache = new LRUCache<UUID, String>(MAX_CACHE_SIZE);
            String testData = "Test Data";
            UUID id = UUID.Random();

            cache.Add(id, testData);
            Assert.IsTrue(cache.Contains(id));
            Assert.AreEqual(1, cache.Size);

            String entry;
            Assert.IsTrue(cache.TryGetValue(id, out entry));
            Assert.AreEqual(testData.Length, entry.Length);
            Assert.AreEqual(1, cache.Size);
        }
Example #16
0
        public void TestPutGet()
        {
            ICache<string, string> cache = new LRUCache<string, string>(4);

            cache.Put("a", "b");
            cache.Put("c", "d");
            cache.Put("e", "f");
            cache.Put("g", "h");

            Assert.Equal(4, cache.Size);

            Assert.Equal("b", cache.Get("a"));
            Assert.Equal("d", cache.Get("c"));
            Assert.Equal("f", cache.Get("e"));
            Assert.Equal("h", cache.Get("g"));
        }
Example #17
0
        public void RemoveLRU_Test()
        {
            var o = new LRUCache<int, string>(5);
            o.Set(1, "one");
            o.Set(2, "two");
            o.Set(3, "three");
            o.Set(4, "four");
            o.Set(5, "five");

            var t = o.Get(5);
            t = o.Get(2);
            t = o.Get(1);
            t = o.Get(5);
            t = o.Get(3);
            o.Set(6, "six"); //should remove 4
            Assert.IsTrue(o.CacheMap.Keys.Any(k => k == 4) == false);
        }
Example #18
0
        public void Clear()
        {
            var dico = new LRUCache<string, int>();

            dico.Set("one", 1);
            dico.Set("two", 2);
            dico.Set("three", 3);
            Assert.AreEqual(1, dico.RawGet("one"));
            Assert.AreEqual(2, dico.RawGet("two"));
            Assert.AreEqual(3, dico.RawGet("three"));
            Assert.AreEqual(3, dico.Count);
            Assert.AreEqual(3, dico.NbUpdate);

            dico.Clear();
            Assert.AreEqual(0, dico.RawGet("one"));
            Assert.AreEqual(0, dico.RawGet("two"));
            Assert.AreEqual(0, dico.RawGet("three"));
            Assert.AreEqual(0, dico.Count);
        }
Example #19
0
        public virtual void Initialize(AbstractClientConfig clientConfig)
        {
            _mClientConfig = clientConfig;
            _mStatistics   = new DefaultMessageStatistics();

            _mFactory = new MessageIdFactory();
            // initialize domain and ip address
            _mFactory.Initialize(_mClientConfig.Domain.Id);

            _mSender = new TcpMessageSender(_mClientConfig, _mStatistics, _mFactory);
            _mSender.Initialize();

            _mStatusUpdateTask = new StatusUpdateTask(_mStatistics, _mClientConfig);

            _mTaggedTransactions = new LRUCache <string, ITaggedTransaction>(CatConstants.TAGGED_TRANSACTION_CACHE_SIZE);

            // start status update task
            ThreadPool.QueueUserWorkItem(_mStatusUpdateTask.Run);

            Logger.Info("Thread(StatusUpdateTask) started.");
        }
Example #20
0
        public void Test()
        {
            //[3],[1,1],[2,2],[3,3],[4,4],[4],[3],[2],[1],[5,5],[1],[2],[3],[4],[5]]
            var l = new LRUCache(3);

            l.Put(1, 1);
            l.Put(2, 2);
            l.Put(3, 3);
            l.Put(4, 4);
            var a1 = l.Get(4);
            var a2 = l.Get(3);
            var a3 = l.Get(2);
            var a4 = l.Get(1);

            l.Put(5, 5);
            var a5 = l.Get(1);
            var a6 = l.Get(2);
            var a7 = l.Get(3);
            var a8 = l.Get(4);
            var a9 = l.Get(5);
        }
Example #21
0
 public void FlushMemoizedIDsForTask(string taskName, string argument)
 {
     if (argument == null)
     {
         if (_MemoizationCache.ContainsKey(taskName))
         {
             _MemoizationCache.Remove(taskName);
         }
     }
     else
     {
         LRUCache <string, object> resultCache = null;
         if (_MemoizationCache.TryGetValue(taskName, out resultCache))
         {
             if (resultCache.ContainsKey(argument))
             {
                 resultCache.Remove(argument);
             }
         }
     }
 }
Example #22
0
        public void TestEviction()
        {
            ICache<string, string> cache = new LRUCache<string, string>(2);

            cache.Put("a", "b");
            cache.Put("c", "d");
            Assert.Equal(2, cache.Size);

            cache.Put("e", "f");
            Assert.Equal(2, cache.Size);
            Assert.Null(cache.Get("a"));
            Assert.Equal("d", cache.Get("c"));
            Assert.Equal("f", cache.Get("e"));

            cache.Get("c");
            cache.Put("g", "h");
            Assert.Equal(2, cache.Size);
            Assert.Null(cache.Get("e"));
            Assert.Equal("d", cache.Get("c"));
            Assert.Equal("h", cache.Get("g"));
        }
Example #23
0
        public void CacheShouldPreserveTheOrder()
        {
            var items = new[] {
                KeyValuePair.Create(1, "One"),
                KeyValuePair.Create(3, "Three"),
                KeyValuePair.Create(2, "Two"),
            };

            ILRUCache <int, string> lruCache = new LRUCache <int, string>(100);

            foreach (var(key, value) in items)
            {
                lruCache.Add(key, value);
            }

            var num = 0;

            foreach (var item in lruCache)
            {
                Assert.AreEqual(items[num++], item);
            }

            Assert.AreEqual("One", lruCache.Lookup(1));
            num = 0;
            foreach (var item in lruCache)
            {
                if (num == 2)
                {
                    Assert.AreEqual(1, item.Key);
                }
                else
                {
                    Assert.AreEqual(items[num + 1], item);
                }
                num++;
            }

            Assert.AreEqual(true, lruCache.TryGet(3, out var threeVal));
            Assert.AreEqual("Three", threeVal);
        }
Example #24
0
        public static void Run()
        {
            var st = new LRUCache(2);

            Console.WriteLine("Start: {0}", DateTime.Now);
            st.Set(2, 1);
            st.Set(2, 2);
            Console.WriteLine(st.Get(2));
            st.Set(1, 1);
            st.Set(4, 1);
            Console.WriteLine(st.Get(2));

            Console.WriteLine("Start: {0}", DateTime.Now);
            var st2 = new LRUCache(1);
            st2.Set(2, 1);
            Console.WriteLine(st2.Get(2));
            st2.Set(3, 2);
            Console.WriteLine(st2.Get(2));
            Console.WriteLine(st2.Get(3));

            Console.WriteLine("End: {0}", DateTime.Now);
        }
Example #25
0
        public void LRUCache_AddAndGetNewItems_Test()
        {
            // Arrange
            var capacity = 10;
            var cache    = new LRUCache <int, string>(capacity);

            // Act
            AddItems(cache, capacity);

            // Assert
            Assert.AreEqual(capacity, cache.Count, "Incorrect item count.");

            for (var i = 0; i < capacity; i++)
            {
                // Act
                var result = cache.TryGetValue(i, out var retrievedValue);

                // Assert
                Assert.IsTrue(result, "Get operation should be successful.");
                Assert.AreEqual(i.ToString(), retrievedValue, "Incorrect item value retrieved.");
            }
        }
Example #26
0
        /// <summary>
        /// Handles post configuration setup
        /// </summary>
        public override void AfterConfigure()
        {
            base.AfterConfigure();
            if (!Directory.Exists(SourceFolder))
            {
                Directory.CreateDirectory(SourceFolder);
            }

            m_filecache = new LRUCache <DateTime>(
                sizelimit: MaxMirrorCacheSize,
                countlimit: MaxMirrorCacheCount,
                expirationHandler: TryDeleteAsync,
                sizeHandler: TryFileSizeAsync
                );

            foreach (var f in Directory.EnumerateFiles(SourceFolder, "*", SearchOption.AllDirectories))
            {
                m_filecache.AddOrReplaceAsync(f, DateTime.Now + StartupMirrorCacheAgeSeconds).Wait();
            }

            m_404cache = new LRUCache <DateTime>(countlimit: Max404CacheCount);
        }
        public void Reset_RemovesAllData()
        {
            var lruCache = new LRUCache <ulong, string>(3);

            lruCache.Put(1, "A");
            lruCache.Put(2, "B");
            lruCache.Put(3, "C");

            Assert.AreEqual(lruCache.priorityQueue.Last.Value, 3UL);
            Assert.AreEqual(lruCache.priorityQueue.First.Value, 1UL);
            Assert.AreEqual(lruCache.CurrentSize, 3);
            Assert.AreEqual(lruCache.itemMap.Count, 3);
            Assert.AreEqual(lruCache.values.Count, 3);

            lruCache.Reset();

            Assert.AreEqual(lruCache.priorityQueue.Last, null);
            Assert.AreEqual(lruCache.priorityQueue.First, null);
            Assert.AreEqual(lruCache.itemMap.Count, 0);
            Assert.AreEqual(lruCache.values.Count, 0);
            Assert.AreEqual(lruCache.CurrentSize, 0);
        }
Example #28
0
        public void LRUTests()
        {
            var cache = new LRUCache(20);

            cache.Put(1, 1);
            cache.Put(2, 2);
            cache.Put(3, 3);
            cache.Put(4, 4);
            cache.Put(5, 5);
            cache.Put(6, 6);

            var head  = cache.GetHead();
            int count = 6;

            while (head != null && head.Previous != null)
            {
                Assert.AreEqual(head.Value, count);
                count--;
                head = head.Previous;
            }

            var value = cache.Get(1);

            Assert.AreEqual(1, value);

            var list = new List <int> {
                2, 3, 4, 5, 6, 1
            };

            var head1  = cache.GetHead();
            int count1 = list.Count - 1;

            while (head1 != null && count1 < list.Count && head1.Previous != null)
            {
                Assert.AreEqual(head1.Value, list[count1]);
                count1--;
                head1 = head1.Previous;
            }
        }
        /// <summary>
        /// Creates a new CH edge data source.
        /// </summary>
        public CHEdgeDataDataSource(Stream stream, CHEdgeDataDataSourceSerializer serializer, IEnumerable <string> vehicles,
                                    int startOfRegions, CHVertexRegionIndex regionIndex, int zoom,
                                    int startOfBlocks, CHBlockIndex blockIndex, uint blockSize,
                                    int startOfShapes, CHBlockIndex shapeIndex,
                                    int startOfReverses, CHBlockIndex reversesIndex,
                                    ITagsCollectionIndexReadonly tagsIndex)
        {
            _stream     = stream;
            _serializer = serializer;
            _vehicles   = new HashSet <string>(vehicles);

            this.InitializeRegions(startOfRegions, regionIndex, zoom);
            this.InitializeBlocks(startOfBlocks, blockIndex, blockSize);
            this.InitializeShapes(startOfShapes, shapeIndex);
            this.InitializeReverses(startOfReverses, reversesIndex);

            _blocks        = new LRUCache <uint, CHBlock>(5000);
            _blockShapes   = new LRUCache <uint, CHBlockCoordinates>(1000);
            _blockReverses = new LRUCache <uint, CHBlockReverse>(1000);
            _regions       = new LRUCache <ulong, CHVertexRegion>(1000);
            _tagsIndex     = tagsIndex;
        }
Example #30
0
        public void TestMethodthread()
        {
            var c = new LRUCache <int, String>(1000);


            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 500; i++)
                {
                    c.Put(i, i.ToString());
                }

                Console.WriteLine(" Put1 [{0}] ", c.Count);
            }

                                  );

            Task.Factory.StartNew(() =>
            {
                for (int i = 500; i < 1000; i++)
                {
                    c.Put(i, i.ToString());
                }
                Console.WriteLine("Put 2 [{0}] ", c.Count);
            }

                                  );


            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    var v = c.Get(i);
                }

                Console.WriteLine("get [{0}] ", c.Count);
            });
        }
Example #31
0
        public void ValueGetterTest()
        {
            int capacity = 700;

            LRUFacade.InitCacheRandom(capacity);
            int j = 0;

            for (int i = 0; i < LRUCache.KeysT.Length; i++)
            {
                if (LRUCache.KeysT[i] == null)
                {
                    break;
                }
                var keyObj   = LRUCache.KeysT[i];
                var checkVal = LRUCache.Get <KeyObjectType, ValueObjectType>((KeyObjectType)keyObj);
                if (checkVal != null)
                {
                    j++;
                }
            }
            Assert.AreEqual(j, LRUCache.WhenLastUsedTicks.Where(s => s != null).Count()); // cache may not be full depending on key/value pair count < capacity
        }
Example #32
0
        public void LRUCache_EntryOrder_ReverseEntryAccess_Test()
        {
            // Arrange
            var capacity = 10;
            var cache    = new LRUCache <int, string>(capacity);

            // Act
            // Set items in sequential order then access in reverse
            AddItems(cache, capacity);
            for (var i = capacity - 1; i >= 0; i--)
            {
                var result = cache.TryGetValue(i, out var retrievedValue);

                // Assert
                Assert.IsTrue(result, "Get operation should be successful.");
                Assert.AreEqual(i.ToString(), retrievedValue, "Cache entry value mismatch.");
            }

            // Assert
            // Entry in cache should now be in increasing order
            VerifyEntrySequence(cache, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        }
Example #33
0
        public void Test4()
        {
            var random = new Random();
            var cache  = new LRUCache <int, int>(1000000);

            for (var i = 0; i < 1000000; i++)
            {
                cache.Add(random.Next(1000000), i);
            }

            var count = 0;

            for (var i = 0; i < 1000000; i++)
            {
                if (cache.Contains(i))
                {
                    count++;
                }
            }

            Assert.AreEqual(0.632, count / 1000000.0, 0.001);
        }
Example #34
0
        public override IList <OsmGeo> Get(GeoCoordinateBox box, Filter filter)
        {
            IList <OsmGeo> osmGeoList = this._source.Get(box, filter);
            long?          id;

            foreach (OsmGeo osmGeo in (IEnumerable <OsmGeo>)osmGeoList)
            {
                switch (osmGeo.Type)
                {
                case OsmGeoType.Node:
                    LRUCache <long, Node> nodesCache = this._nodesCache;
                    id = osmGeo.Id;
                    long key1 = id.Value;
                    Node node = osmGeo as Node;
                    nodesCache.Add(key1, node);
                    continue;

                case OsmGeoType.Way:
                    LRUCache <long, Way> waysCache = this._waysCache;
                    id = osmGeo.Id;
                    long key2 = id.Value;
                    Way  way  = osmGeo as Way;
                    waysCache.Add(key2, way);
                    continue;

                case OsmGeoType.Relation:
                    LRUCache <long, Relation> relationsCache = this._relationsCache;
                    id = osmGeo.Id;
                    long     key3     = id.Value;
                    Relation relation = osmGeo as Relation;
                    relationsCache.Add(key3, relation);
                    continue;

                default:
                    continue;
                }
            }
            return(osmGeoList);
        }
Example #35
0
        public void TestEvictionPolicy()
        {
            LRUCache <string, string> cache = new LRUCache <string, string>(100);

            for (int i = 0; i < 1000; i++)
            {
                cache.Put(i.ToString(), i.ToString());
            }

            Assert.AreEqual(cache.Size, 100);
            Assert.AreEqual(cache.EvictionCount, 900);

            for (int i = 0; i < 900; i++)
            {
                Assert.AreEqual(cache.Get(i.ToString()), null);
            }

            for (int i = 900; i < 1000; i++)
            {
                Assert.AreEqual(cache.Get(i.ToString()), i.ToString());
            }
        }
Example #36
0
        public Emulation()
        {
            syncDomains      = new List <ISynchronizationDomain>();
            HostMachine      = new HostMachine();
            MACRepository    = new MACRepository();
            ExternalsManager = new ExternalsManager();
            ExternalsManager.AddExternal(HostMachine, HostMachine.HostMachineName);
            Connector       = new Connector();
            FileFetcher     = new CachingFileFetcher();
            CurrentLogger   = Logger.GetLogger();
            randomGenerator = new Lazy <PseudorandomNumberGenerator>(() => new PseudorandomNumberGenerator());
            nameCache       = new LRUCache <object, Tuple <string, string> >(NameCacheSize);

            machs            = new FastReadConcurrentTwoWayDictionary <string, Machine>();
            machs.ItemAdded += (name, machine) =>
            {
                machine.StateChanged       += OnMachineStateChanged;
                machine.PeripheralsChanged += (m, e) =>
                {
                    if (e.Operation != PeripheralsChangedEventArgs.PeripheralChangeType.Addition)
                    {
                        nameCache.Invalidate();
                    }
                };

                OnMachineAdded(machine);
            };

            machs.ItemRemoved += (name, machine) =>
            {
                machine.StateChanged -= OnMachineStateChanged;
                nameCache.Invalidate();

                OnMachineRemoved(machine);
            };
            BackendManager = new BackendManager();
            BlobManager    = new BlobManager();
            theBag         = new Dictionary <string, object>();
        }
        /// <summary>
        /// Creates a memory mapped huge array.
        /// </summary>
        /// <param name="file">The the memory mapped file.</param>
        /// <param name="elementSize">The element size.</param>
        /// <param name="size">The initial size of the array.</param>
        /// <param name="arraySize">The size of an indivdual array block.</param>
        /// <param name="bufferSize">The size of an idividual buffer.</param>
        /// <param name="cacheSize">The size of the LRU cache to keep buffers.</param>
        public MemoryMappedHugeArray(MemoryMappedFile file, int elementSize, long size, long arraySize, int bufferSize, int cacheSize)
        {
            if (file == null)
            {
                throw new ArgumentNullException();
            }
            if (elementSize < 0)
            {
                throw new ArgumentOutOfRangeException("elementSize");
            }
            if (arraySize < 0)
            {
                throw new ArgumentOutOfRangeException("arraySize");
            }
            if (size < 0)
            {
                throw new ArgumentOutOfRangeException("size");
            }

            _file            = file;
            _length          = size;
            _fileElementSize = arraySize;
            _elementSize     = elementSize;
            _fileSizeBytes   = arraySize * _elementSize;

            _bufferSize              = bufferSize;
            _cachedBuffer            = null;
            _cachedBuffers           = new LRUCache <long, CachedBuffer>(cacheSize);
            _cachedBuffers.OnRemove += new LRUCache <long, CachedBuffer> .OnRemoveDelegate(buffer_OnRemove);

            var arrayCount = (int)System.Math.Ceiling((double)size / _fileElementSize);

            _accessors = new List <MemoryMappedAccessor <T> >(arrayCount);
            for (int arrayIdx = 0; arrayIdx < arrayCount; arrayIdx++)
            {
                _accessors.Add(this.CreateAccessor(_file, _fileSizeBytes));
            }
        }
Example #38
0
    private void Start()
    {
        loadQueue = new Queue <Vector3Int>();
        gridMap   = new GridMap();
        gridMap.RegisterCreateOnMissChunkMethod(CreateOnMissChunk);
        gridMap.RegisterOnSetValueMethod(OnGridmapSetValue);

        StartCoroutine(ChunkLoaderCoroutine());

        Texture2D minimapTexture = new Texture2D(144, 144);

        minimap.sprite = Sprite.Create(minimapTexture, new Rect(0, 0, 144, 144), new Vector2(0.5f, 0.5f));

        Color[] emptyColors = new Color[spriteSize * Chunk.chunkSize * spriteSize * Chunk.chunkSize];
        for (int i = 0; i < spriteSize * Chunk.chunkSize * spriteSize * Chunk.chunkSize; i++)
        {
            emptyColors[i] = Color.clear;
        }

        RenderedChunk[] renderedChunks = new RenderedChunk[chunkCapacity];
        for (int i = 0; i < chunkCapacity; i++)
        {
            GameObject go = new GameObject("Chunk" + i);
            go.transform.parent = transform;
            SpriteRenderer renderer = go.AddComponent <SpriteRenderer>();
            Texture2D      texture  = new Texture2D(spriteSize * Chunk.chunkSize, spriteSize * Chunk.chunkSize);
            texture.SetPixels(emptyColors);
            texture.Apply();
            texture.filterMode = FilterMode.Point;
            renderer.sprite    = Sprite.Create(texture, new Rect(0, 0, spriteSize * Chunk.chunkSize, spriteSize * Chunk.chunkSize), new Vector2(0, 0), spriteSize);
            renderedChunks[i]  = go.AddComponent <RenderedChunk>();
            renderer.gameObject.SetActive(false);
        }

        chunkCache = new LRUCache <Vector3Int, RenderedChunk>(chunkCapacity, true, renderedChunks);
        chunkCache.registerOnRemoveMethod(OnReleaseChunk);
        Load(SceneData.Instance.isNewMap);
    }
Example #39
0
        public static void LRUCache()
        {
            LeastRecentlyUsedCache cache = new LeastRecentlyUsedCache(2);

            cache.Set(1, 10);
            cache.Set(5, 12);

            Assert.That(cache.Get(5) == 12);
            Assert.That(cache.Get(1) == 10);
            Assert.That(cache.Get(10) == -1);

            cache.Set(6, 14);
            Assert.That(cache.Get(5) == -1);

            LRUCache cache2 = new LRUCache(2);

            cache2.Put(2, 1);
            cache2.Put(1, 1);
            cache2.Get(2);
            cache2.Put(4, 1);
            cache2.Get(1);
            cache2.Get(2);
        }
Example #40
0
        public InternalAuthenticationProvider(ISubscriber subscriber, IODispatcher ioDispatcher, PasswordHashAlgorithm passwordHashAlgorithm,
                                              int cacheSize, bool logFailedAuthenticationAttempts)
        {
            _ioDispatcher                    = ioDispatcher;
            _passwordHashAlgorithm           = passwordHashAlgorithm;
            _userPasswordsCache              = new LRUCache <string, Tuple <string, ClaimsPrincipal> >(cacheSize);
            _logFailedAuthenticationAttempts = logFailedAuthenticationAttempts;

            var userManagement = new UserManagementService(ioDispatcher, _passwordHashAlgorithm,
                                                           skipInitializeStandardUsersCheck: false, _tcs);

            subscriber.Subscribe <UserManagementMessage.Create>(userManagement);
            subscriber.Subscribe <UserManagementMessage.Update>(userManagement);
            subscriber.Subscribe <UserManagementMessage.Enable>(userManagement);
            subscriber.Subscribe <UserManagementMessage.Disable>(userManagement);
            subscriber.Subscribe <UserManagementMessage.Delete>(userManagement);
            subscriber.Subscribe <UserManagementMessage.ResetPassword>(userManagement);
            subscriber.Subscribe <UserManagementMessage.ChangePassword>(userManagement);
            subscriber.Subscribe <UserManagementMessage.Get>(userManagement);
            subscriber.Subscribe <UserManagementMessage.GetAll>(userManagement);
            subscriber.Subscribe <SystemMessage.BecomeLeader>(userManagement);
            subscriber.Subscribe <SystemMessage.BecomeFollower>(userManagement);
        }
Example #41
0
        public void TestRemove()
        {
            ICache<string, string> cache = new LRUCache<string, string>(4);

            cache.Put("a", "b");
            cache.Put("c", "d");
            cache.Put("e", "f");

            Assert.Equal(3, cache.Size);
            Assert.Equal(true, cache.Remove("a"));
            Assert.Equal(2, cache.Size);
            Assert.Null(cache.Get("a"));
            Assert.Equal("d", cache.Get("c"));
            Assert.Equal("f", cache.Get("e"));
            Assert.Equal(false, cache.Remove("KeyDoesNotExist"));
            Assert.Equal(true, cache.Remove("c"));
            Assert.Equal(1, cache.Size);
            Assert.Null(cache.Get("c"));
            Assert.Equal("f", cache.Get("e"));
            Assert.Equal(true, cache.Remove("e"));
            Assert.Equal(0, cache.Size);
            Assert.Null(cache.Get("e"));
        }
Example #42
0
        public static void TestReplace()
        {
            var cache = new LRUCache <string, int>(3);

            cache["a"] = 1;
            cache["b"] = 2;
            cache["c"] = 3;

            int x = default;

            x = cache["a"];
            x = cache["a"];
            x = cache["b"];

            cache["d"] = 4;
            cache["e"] = 5;

            Assert.IsFalse(cache.ContainsKey("a"));
            Assert.AreEqual(cache["b"], 2, "should get 2");
            Assert.IsFalse(cache.ContainsKey("c"));
            Assert.AreEqual(cache["d"], 4, "should get 4");
            Assert.AreEqual(cache["e"], 5, "should get 5");
        }
Example #43
0
        public void TestCase()
        {
            var cache = new LRUCache(3);

            cache.Put(1, 1);
            cache.Put(2, 2);
            cache.Put(3, 3);
            cache.Put(3, 5);
            cache.Put(4, 4);
            cache.Put(1, 4);
            Assert.AreEqual(4, cache.Get(4));
            Assert.AreEqual(-1, cache.Get(5));
            Assert.AreEqual(5, cache.Get(3));
            Assert.AreEqual(-1, cache.Get(2));
            cache.Put(3, 10);
            Assert.AreEqual(4, cache.Get(1));
            cache.Put(5, 5);
            Assert.AreEqual(-1, cache.Get(1));
            Assert.AreEqual(10, cache.Get(3));
            Assert.AreEqual(4, cache.Get(4));
            cache.Put(6, 1);
            Assert.AreEqual(-1, cache.Get(4));
        }
Example #44
0
        public ContextControllerInitTermOverlap(
            ContextControllerInitTermFactory factory,
            ContextManagerRealization realization)
            : base(factory, realization)

        {
            if (factory.InitTermSpec.DistinctEval != null) {
                if (factory.FactoryEnv.NumNestingLevels == 1) {
                    distinctSvc = new ContextControllerInitTermDistinctSvcNonNested();
                }
                else {
                    distinctSvc = new ContextControllerInitTermDistinctSvcNested();
                }

                eventsPerStreamDistinct = new EventBean[1];
                distinctLastTriggerEvents = new LRUCache<object, EventBean>(16);
            }
            else {
                distinctSvc = null;
                distinctLastTriggerEvents = null;
                eventsPerStreamDistinct = null;
            }
        }
Example #45
0
        public void TestOverflowReplacesFirstEntryAdded()
        {
            var cache = new LRUCache <UUID, string>(10);

            UUID   firstEntryId   = UUID.Random();
            string firstEntryData = "First Entry";

            cache.Add(firstEntryId, firstEntryData);

            string testData = "Test Data";

            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count, "Count property was wrong");
            Assert.AreEqual(10, cache.Size, "Size property was wrong");

            Assert.IsFalse(cache.TryGetValue(firstEntryId, out string lastInsertedValue));
            Assert.IsNull(lastInsertedValue);
        }
Example #46
0
    public static void Main(string[] args)
    {
        int noOfTC = Convert.ToInt32(Console.ReadLine());

        for (int t = 0; t < noOfTC; ++t)
        {
            ////int num = Convert.ToInt32(Console.ReadLine());
            //string[] s1 = Console.ReadLine().Split(' ');
            ////int[] arr = Array.ConvertAll(s1, int.Parse);
            ////string str = Console.ReadLine();
            //int i = 0;
            LRUCache lru = new LRUCache(3);
            lru.set(1, 3);
            lru.set(2, 4);
            Console.WriteLine(lru.get(2));
            lru.set(5, 6);
            lru.set(1, 8);
            Console.WriteLine(lru.get(1));
            lru.set(12, 14);
            Console.WriteLine(lru.get(2));
        }
        Console.ReadLine();
    }
Example #47
0
        public void CacheShouldRemoveLeasRecentlyUsedItems()
        {
            var items = new[] {
                KeyValuePair.Create(1, "One"),
                KeyValuePair.Create(3, "Three"),
                KeyValuePair.Create(2, "Two"),
                KeyValuePair.Create(5, "Five"),
                KeyValuePair.Create(4, "Four"),
            };

            ILRUCache <int, string> lruCache = new LRUCache <int, string>(2);

            foreach (var(key, value) in items)
            {
                lruCache.Add(key, value);
            }

            var cacheElements = lruCache.ToArray();

            Assert.AreEqual(2, cacheElements.Length);
            Assert.AreEqual(5, cacheElements[0].Key);
            Assert.AreEqual(4, cacheElements[1].Key);

            lruCache.Lookup(5);
            cacheElements = lruCache.ToArray();
            Assert.AreEqual(2, cacheElements.Length);
            Assert.AreEqual(4, cacheElements[0].Key);
            Assert.AreEqual(5, cacheElements[1].Key);

            for (var i = 1; i <= 3; i++)
            {
                Assert.False(lruCache.Contains(i));
            }
            Assert.True(lruCache.Contains(4));
            Assert.True(lruCache.Contains(5));
        }
Example #48
0
    public void InitSvc(MonoBehaviour mono, bool isRunTime)
    {
        this.mono = mono;
#if UNITY_EDITOR
        if (isRunTime)
        {
            loader = new ResRuntimeLoader();
        }
        else
        {
            loader = new ResEditorLoader();
        }
#else
        loader = new ResRuntimeLoader();
#endif
        noRefResCache = new LRUCache <ResItemInfo>(Constants.LRUCache);
        loader.Init();

        for (int i = 0; i < (int)ResPriority.MaxPriority; ++i)
        {
            loadingAssetTaskList[i] = new List <AsyncLoadResTask>();
        }
        this.mono.StartCoroutine(AsyncLoader());
    }
Example #49
0
        public void SetGet()
        {
            var dico = new LRUCache<string, int>();

            dico.Set("the answer", 42);
            Assert.AreEqual(42, dico.RawGet("the answer"));
            Assert.AreEqual(1, dico.Count);
            Assert.AreEqual(1, dico.NbUpdate);
            Assert.AreEqual(0, dico.NbHit);
            Assert.AreEqual(1, dico.NbMiss);
            Assert.AreEqual(0, dico.NbEviction);

            int fortytwo = dico.Get("the answer");
            Assert.AreEqual(42, fortytwo);
            Assert.AreEqual(1, dico.Count);
            Assert.AreEqual(1, dico.NbUpdate);
            Assert.AreEqual(1, dico.NbHit);
            Assert.AreEqual(1, dico.NbMiss);
            Assert.AreEqual(0, dico.NbEviction);

            int fortythree = dico.Get("the wrong answer");
            Assert.AreEqual(0, fortythree);
            Assert.AreEqual(1, dico.Count);
            Assert.AreEqual(1, dico.NbUpdate);
            Assert.AreEqual(1, dico.NbHit);
            Assert.AreEqual(2, dico.NbMiss);
            Assert.AreEqual(0, dico.NbEviction);

            dico.Set("the answer", 24);
            Assert.AreEqual(24, dico.RawGet("the answer"));
            Assert.AreEqual(1, dico.Count);
            Assert.AreEqual(2, dico.NbUpdate);
            Assert.AreEqual(2, dico.NbHit);
            Assert.AreEqual(2, dico.NbMiss);
            Assert.AreEqual(0, dico.NbEviction);
        }
Example #50
0
        public void LRUCache_AddAndIndexNewItems_Test()
        {
            // Arrange
            var capacity = 10;
            var cache    = new LRUCache <int, string>(capacity);

            // Act
            for (var i = 0; i < capacity; i++)
            {
                cache[i] = i.ToString();
            }

            // Assert
            Assert.AreEqual(capacity, cache.Count, "Incorrect item count.");

            for (var i = 0; i < capacity; i++)
            {
                string retrievedValue = string.Empty;
                Assert.DoesNotThrow(() => retrievedValue = cache[i]);
                Assert.AreEqual(i.ToString(), retrievedValue, "Incorrect item value retrieved.");
            }

            Assert.Throws <KeyNotFoundException>(() => _ = cache[capacity]);
        }
Example #51
0
        public void FailedCase13()
        {
            //input["LRUCache","put","put","put","put","put","get","put","get","get","put","get","put","put","put","get","put","get","get","get","get","put","put","get","get","get","put","put","get","put","get","put","get","get","get","put","put","put","get","put","get","get","put","put","get","put","put","put","put","get","put","put","get","put","put","get","put","put","put","put","put","get","put","put","get","put","get","get","get","put","get","get","put","put","put","put","get","put","put","put","put","get","get","get","put","put","put","get","put","put","put","get","put","put","put","get","get","get","put","put","put","put","get","put","put","put","put","put","put","put"]
            //[[10],[10,13],[3,17],[6,11],[10,5],[9,10],[13],[2,19],[2],[3],[5,25],[8],[9,22],[5,5],[1,30],[11],[9,12],[7],[5],[8],[9],[4,30],[9,3],[9],[10],[10],[6,14],[3,1],[3],[10,11],[8],[2,14],[1],[5],[4],[11,4],[12,24],[5,18],[13],[7,23],[8],[12],[3,27],[2,12],[5],[2,9],[13,4],[8,18],[1,7],[6],[9,29],[8,21],[5],[6,30],[1,12],[10],[4,15],[7,22],[11,26],[8,17],[9,29],[5],[3,4],[11,30],[12],[4,29],[3],[9],[6],[3,4],[1],[10],[3,29],[10,28],[1,20],[11,13],[3],[3,12],[3,8],[10,9],[3,26],[8],[7],[5],[13,17],[2,27],[11,15],[12],[9,19],[2,15],[3,16],[1],[12,17],[9,1],[6,19],[4],[5],[5],[8,1],[11,7],[5,2],[9,28],[1],[2,2],[7,4],[4,22],[7,24],[9,26],[13,28],[11,26]]
            //output[null,null,null,null,null,null,-1,null,19,17,null,-1,null,null,null,-1,null,-1,5,-1,12,null,null,3,5,5,null,null,1,null,-1,null,30,5,30,null,null,null,-1,null,-1,24,null,null,18,null,null,null,null,14,null,null,18,null,null,-1,null,null,null,null,null,18,null,null,24,null,4,-1,30,null,12,-1,null,null,null,null,29,null,null,null,null,17,22,-1,null,null,null,24,null,null,null,-1,null,null,null,-1,-1,-1,null,null,null,null,-1,null,null,null,null,null,null,null]
            //expected [null,null,null,null,null,null,-1,null,19,17,null,-1,null,null,null,-1,null,-1,5,-1,12,null,null,3,5,5,null,null,1,null,-1,null,30,5,30,null,null,null,-1,null,-1,24,null,null,18,null,null,null,null,-1,null,null,18,null,null,-1,null,null,null,null,null,18,null,null,-1,null,4,29,30,null,12,-1,null,null,null,null,29,null,null,null,null,17,22,18,null,null,null,-1,null,null,null,20,null,null,null,-1,18,18,null,null,null,null,20,null,null,null,null,null,null,null]
            var cache      = new LRUCache(10);
            var commands   = new string[] { "put", "put", "put", "put", "put", "get", "put", "get", "get", "put", "get", "put", "put", "put", "get", "put", "get", "get", "get", "get", "put", "put", "get", "get", "get", "put", "put", "get", "put", "get", "put", "get", "get", "get", "put", "put", "put", "get", "put", "get", "get", "put", "put", "get", "put", "put", "put", "put", "get", "put", "put", "get", "put", "put", "get", "put", "put", "put", "put", "put", "get", "put", "put", "get", "put", "get", "get", "get", "put", "get", "get", "put", "put", "put", "put", "get", "put", "put", "put", "put", "get", "get", "get", "put", "put", "put", "get", "put", "put", "put", "get", "put", "put", "put", "get", "get", "get", "put", "put", "put", "put", "get", "put", "put", "put", "put", "put", "put", "put" };
            var parameters = new int[, ] {
                { 10, 13 }, { 3, 17 }, { 6, 11 }, { 10, 5 }, { 9, 10 }, { 13, 0 }, { 2, 19 }, { 2, 0 }, { 3, 0 }, { 5, 25 }, { 8, 0 }, { 9, 22 }, { 5, 5 }, { 1, 30 }, { 11, 0 }, { 9, 12 }, { 7, 0 }, { 5, 0 }, { 8, 0 }, { 9, 0 }, { 4, 30 }, { 9, 3 }, { 9, 0 }, { 10, 0 }, { 10, 0 }, { 6, 14 }, { 3, 1 }, { 3, 0 }, { 10, 11 }, { 8, 0 }, { 2, 14 }, { 1, 0 }, { 5, 0 }, { 4, 0 }, { 11, 4 }, { 12, 24 }, { 5, 18 }, { 13, 0 }, { 7, 23 }, { 8, 0 }, { 12, 0 }, { 3, 27 }, { 2, 12 }, { 5, 0 }, { 2, 9 }, { 13, 4 }, { 8, 18 }, { 1, 7 }, { 6, 0 }, { 9, 29 }, { 8, 21 }, { 5, 0 }, { 6, 30 }, { 1, 12 }, { 10, 0 }, { 4, 15 }, { 7, 22 }, { 11, 26 }, { 8, 17 }, { 9, 29 }, { 5, 0 }, { 3, 4 }, { 11, 30 }, { 12, 0 }, { 4, 29 }, { 3, 0 }, { 9, 0 }, { 6, 0 }, { 3, 4 }, { 1, 0 }, { 10, 0 }, { 3, 29 }, { 10, 28 }, { 1, 20 }, { 11, 13 }, { 3, 0 }, { 3, 12 }, { 3, 8 }, { 10, 9 }, { 3, 26 }, { 8, 0 }, { 7, 0 }, { 5, 0 }, { 13, 17 }, { 2, 27 }, { 11, 15 }, { 12, 0 }, { 9, 19 }, { 2, 15 }, { 3, 16 }, { 1, 0 }, { 12, 17 }, { 9, 1 }, { 6, 19 }, { 4, 0 }, { 5, 0 }, { 5, 0 }, { 8, 1 }, { 11, 7 }, { 5, 2 }, { 9, 28 }, { 1, 0 }, { 2, 2 }, { 7, 4 }, { 4, 22 }, { 7, 24 }, { 9, 26 }, { 13, 28 }, { 11, 26 }
            };
            var expected = new int?[]
            {
                null, null, null, null, null, -1, null, 19, 17, null, -1, null, null, null, -1, null, -1, 5, -1,
                12, null, null, 3, 5, 5, null, null, 1, null, -1, null, 30, 5, 30, null, null, null, -1, null, -1, 24,
                null, null, 18, null, null, null, null, -1, null, null, 18, null, null, -1, null, null, null, null,
                null, 18, null, null, -1, null, 4, 29, 30, null, 12, -1, null, null, null, null, 29, null, null, null,
                null, 17, 22, 18, null, null, null, -1, null, null, null, 20, null, null, null, -1, 18, 18, null, null,
                null, null, 20, null, null, null, null, null, null, null
            };

            for (int i = 0; i < commands.Length; i++)
            {
                var command = commands[i];
                switch (command)
                {
                case "put":
                    cache.Put(parameters[i, 0], parameters[i, 1]);
                    break;

                case "get":
                    Assert.Equal(expected[i], cache.Get(parameters[i, 0]));
                    break;
                }
            }
        }
        public void TestConcurrentCache()
        {
            const int N = 10000, M = 400;
            var       cache = new LRUCache <string, string>(TimeSpan.FromDays(1), GetCache, null, 3);

            string[] strs  = { "a", "b", "c", "d" };
            var      tasks = new List <Task>();

            for (int i = 0; i < N; ++i)
            {
                tasks.Add(Task.Run(() =>
                {
                    for (int j = 0; j < M; ++j)
                    {
                        cache.Get(strs[j % 4]);
                    }
                }));
            }
            Task.WaitAll(tasks.ToArray());

            Assert.IsTrue(cache.IsValid("b"));
            Assert.IsTrue(cache.IsValid("c"));
            Assert.IsTrue(cache.IsValid("d"));
        }
		/// <summary>
		///   Creates a new instance of the image loader
		/// </summary>
		/// <param name="cacheSize">
		/// The maximum number of entries in the LRU cache
		/// </param>
		/// <param name="memoryLimit">
		/// The maximum number of bytes to consume by the image loader cache.
		/// </param>
		public ImageLoader(int cacheSize, int memoryLimit)
		{
			cache = new LRUCache<Uri, UIImage>(cacheSize, memoryLimit, sizer);
		}
Example #54
0
        public void TestAgingRemovesEntriesUsingBytesForReservedSize()
        {
            UUID firstEntryId = UUID.Random();
            String firstEntryData = "First Entry";

            UUID secondEntryId = UUID.Random();
            String secondEntryData = "Second Entry";

            var cache = new LRUCache<UUID, String>(capacity: 250, useSizing: true, minSize: secondEntryData.Length, maxAge: 1000);
            cache.Add(firstEntryId, firstEntryData, firstEntryData.Length);
            cache.Add(secondEntryId, secondEntryData, secondEntryData.Length);

            Thread.Sleep(5 * 1000);
            cache.Maintain();

            Assert.AreEqual(1, cache.Count);
            Assert.AreEqual(secondEntryData.Length, cache.Size);

            String lastInsertedValue;
            Assert.IsFalse(cache.TryGetValue(firstEntryId, out lastInsertedValue));
            Assert.IsNull(lastInsertedValue);

            Assert.IsTrue(cache.TryGetValue(secondEntryId, out lastInsertedValue));
            Assert.AreEqual(secondEntryData, lastInsertedValue);
        }
 private void EvictionHandler (object sender, LRUCache<ChunkKey, ChunkRef>.CacheValueArgs e)
 {
     if (e.Value.IsDirty) {
         _dirty[e.Key] = e.Value;
     }
 }
		/// <summary>
		///   Creates a new instance of the image loader
		/// </summary>
		/// <param name="cacheSize">
		/// The maximum number of entries in the LRU cache
		/// </param>
		/// <param name="memoryLimit">
		/// The maximum number of bytes to consume by the image loader cache.
		/// </param>
		public ImageLoader(int cacheSize, int memoryLimit)
		{
			cache = new LRUCache<Uri, Drawable /*UIImage*/>(cacheSize, memoryLimit, sizer);
		}
Example #57
0
        static ImageStore()
        {
            PicDir = Path.Combine (Util.BaseDir, "Library/Caches/Pictures/");
            RoundedPicDir = Path.Combine (PicDir, "Rounded/");
            LargeRoundedPicDir = Path.Combine (PicDir, "LargeRounded/");
            TmpDir = Path.Combine (Util.BaseDir, "tmp/");

            if (!Directory.Exists (PicDir))
                Directory.CreateDirectory (PicDir);

            if (!Directory.Exists (RoundedPicDir))
                Directory.CreateDirectory (RoundedPicDir);

            if (!Directory.Exists (LargeRoundedPicDir))
                Directory.CreateDirectory (LargeRoundedPicDir);

            DefaultImage = UIImage.FromFile ("Images/default_profile_4_normal.png");
            cache = new LRUCache<long,UIImage> (200);
            pendingRequests = new Dictionary<long,List<IImageUpdated>> ();
            #if DEBUGIMAGE
            pendingTimes = new Dictionary<long, long> ();
            #endif
            idToUrl = new Dictionary<long,string> ();
            queuedUpdates = new HashSet<long>();
            requestQueue = new Stack<long> ();
        }
Example #58
0
        public void TestFillCache()
        {
            var cache = new LRUCache<UUID, String>(10);
            String testData = "Test Data";

            for (int i = 0; i < 10; i++)
            {
                var id = UUID.Random();
                cache.Add(id, testData);
            }

            Assert.AreEqual(10, cache.Count);
            Assert.AreEqual(10, cache.Size);
        }
        /// <summary>
        /// Creates a new instance of LRU cache where elements are evicted based on least frequently usage.
        /// </summary>
        static void testLRUCache()
        {
            ComputerInfo computerInfo = new ComputerInfo(); //reference to Microsoft.VisualBasic assembly.

            var lru = new LRUCache<int, Image<Gray, byte>>(
                                                    (currentSize) =>
                                                    {
                                                        var occupied = computerInfo.TotalPhysicalMemory - computerInfo.AvailablePhysicalMemory;
                                                        var occupiedPercentage = (float)occupied / computerInfo.TotalPhysicalMemory;

                                                        if (occupiedPercentage > 0.85)
                                                            return true;

                                                        return false;
                                                    },
                                                    (img) => (ulong)(img.Stride * img.Height));

            lru.OnRemoveItem += lru_OnRemoveItem;

            /***************** add some elements ****************/
            var image = new Image<Gray, byte>(5 * 1024 * 1024, 1, 0);
            image.SetValue(5 % 256);
            lru.Add(1, image);

            image = new Image<Gray, byte>(5 * 1024 * 1024, 1, 0);
            image.SetValue(5 % 256);
            lru.Add(1, image);
            /***************** add some elements ****************/

            List<Image<Gray, byte>> a = new List<Image<Gray, byte>>();

            Random rand = new Random();

            int i = 0;
            while (i < 10000)
            {
                image = new Image<Gray, byte>(1024 * 1024, 1, 0);
                image.SetValue(i % 256);
                lru.Add(i, image);

                //Thread.Sleep(1);
                Console.WriteLine(computerInfo.AvailablePhysicalMemory / 1024 / 1024);
                i++;
            }

            //discover more properties and methods!
        }
Example #60
0
 private void InitializeInternals()
 {
     Lock();
     try
     {
         objectCache = new LRUCache<string, IDictionary<string, ICmisObject>>(cacheSize, TimeSpan.FromMilliseconds(cacheTtl));
         pathToIdCache = new LRUCache<string, string>(pathToIdSize, TimeSpan.FromMilliseconds(pathToIdTtl));
     }
     finally
     {
         Unlock();
     }
 }