/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cache; import java.util.ArrayList; /** * * @author Juninho Carlos */ public class LRU { ArrayList traceLRU; private boolean firstTime; private int TAM; public LRU(){ this.TAM = 4; this.firstTime = true; this.traceLRU = new ArrayList<>(); } public ArrayList getTraceLRU(){ return this.traceLRU; } private boolean isCheio(){ return this.traceLRU.size() == TAM; } private int getIndexFromBloco(int num_bloco){ for(int i = 0; i < this.traceLRU.size(); i++){ if(this.traceLRU.get(i) == num_bloco){ return i; } } return -1; } private boolean containsBloco(int num_bloco){ for(int i = 0; i < this.traceLRU.size(); i++){ if(this.traceLRU.get(i) == num_bloco){ return true; } } return false; } private void atualizaTraceLRU(int indexDoAcesso){ int bloco = this.traceLRU.get(indexDoAcesso); for(; indexDoAcesso < this.traceLRU.size()-1; indexDoAcesso++){ this.traceLRU.set(indexDoAcesso,this.traceLRU.get(indexDoAcesso+1)); } this.traceLRU.set(indexDoAcesso, bloco); } private void insereNoFinal(int numBloco){ this.traceLRU.add(numBloco); } public void atualizaLRU(int bloco){ //Caso o trace ainda não tenha sido preenchido if(!isCheio() && containsBloco(bloco)){ this.atualizaTraceLRU(getIndexFromBloco(bloco)); return; }else if(!isCheio()){ this.insereNoFinal(bloco); return; } //Caso já tenha sido preenchido int indiceBloco = 0; for(; indiceBloco < this.traceLRU.size(); indiceBloco++){ if(this.traceLRU.get(indiceBloco) == bloco){ break; } } for(; indiceBloco < this.traceLRU.size()-1;indiceBloco++){ this.traceLRU.set(indiceBloco, this.traceLRU.get(indiceBloco+1)); } this.traceLRU.set(this.traceLRU.size()-1, bloco); } public int getBlocoFromLru(){ if(this.firstTime){ this.firstTime = false; this.TAM = this.traceLRU.size(); } if(this.traceLRU.isEmpty()){ return -1; } return this.traceLRU.get(0); } @Override public String toString() { String s = this.traceLRU.toString(); s += "\n"; return s; //To change body of generated methods, choose Tools | Templates. } }