// This method gets called when ever there was a MISS or Cache need // to be reorganized in case if it reached to its capacity to hold entries. void set(Key key, Value data) { Entry<Key,Value>* node = hash[key]; if(node) { // refresh the link list entries->remove(node); node->data = data; entries->addInFront(node); } else{ if ( cacheFull() ){ node = entries->tail->prev; entries->remove(node); hash.erase(node->key); node->key = key; node->data = data; hash[key] = node; entries->addInFront(node); } else{ node = new Entry<Key,Value>; node->key = key; node->data = data; hash[key] = node; entries->addInFront(node); } } }
// It does the respective part. It checks if the requested key is in the // cache lookup table, if it finds, which is a HIT, it returns the userName // if it was a MISS, it gets the data from the external data source which // could be a database or file in real time, but an In Memory map in our case // and updates the map with set method. Value get(Key key) { prnt(); if(hash.count(key)==1) { Entry<Key,Value>* node = hash[key]; cout << "<HIT> --> requested UserID found in Cache."; entries->remove(node); entries->addInFront(node); return node->data; } else{ // not found in cache, read from external source and create entry cout << "<MISS> --> UserID not found in Cache, Reading from Memory\n"; string userName = externalData.getUserByID(key); if (userName.length() > 0){ set(key, userName); } return userName; } }