public class AssociativeCache extends Cache { public AssociativeCache(int aCacheSize, int aBlockSize) { super(aCacheSize, aBlockSize); } public void loadAssociativeCache(int anInstruction, Memory aMemory) { int memoryRow = anInstruction / Memory.getBlockSize(); int aTag = memoryRow; if (compareTags(aTag)) { System.out.println("This is a HIT"); hits++; LRUUpdate(); } else if (isThereFreeSpace()) { System.out.println("There is free space left so miss"); cache[getFreeSpaceIndex()].loadBlock(aMemory.returnBlock(memoryRow), aTag); misses++; LRUUpdate(); } else { System.out.println("Cache full, checking LRU, MISS"); int change = getLeastRecentlyUsedIndex(getHighestLRU()); cache[change].loadBlock(aMemory.returnBlock(memoryRow), aTag); misses++; LRUUpdate(); } } public void LRUUpdate() { for(int i = 0; i < cache.length; i++) { if (cache[i].getValidityBit() == true) { cache[i].setLRU(cache[i].getLRU()+1); } } } public boolean isThereFreeSpace() { boolean condition = false; for (int i = 0; i < cache.length; i++) { if (cache[i].getValidityBit()== false) { condition = true; break; } } return condition; } public int getFreeSpaceIndex() { int freeSpaceIndex = 0; for (int i = 0; i < cache.length; i++) { if (cache[i].getValidityBit()== false) { freeSpaceIndex = i; break; } } return freeSpaceIndex; } public boolean compareTags(int aTag) { boolean flag = false; for (int i = 0; i < cache.length; i++) { if (cache[i].getCacheTag() == aTag) { flag = true; break; } } return flag; } public int getHighestLRU() { int highestLRU = 0; for (int i = 0; i < cache.length; i ++) { if (cache[i].getLRU() > highestLRU) { highestLRU = cache[i].getLRU(); } } return highestLRU; } public int getLeastRecentlyUsedIndex(int aHighestLRU) { int leastRecentlyUsedIndex = 0; for (int i = 0; i < cache.length; i++) { if (cache[i].getLRU() == aHighestLRU) { leastRecentlyUsedIndex = i; } } return leastRecentlyUsedIndex; } }