LRU.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package cache;
  7. import java.util.ArrayList;
  8. /**
  9. *
  10. * @author Juninho Carlos
  11. */
  12. public class LRU {
  13. ArrayList<Integer> traceLRU;
  14. private boolean firstTime;
  15. private int TAM;
  16. public LRU(){
  17. this.TAM = 4;
  18. this.firstTime = true;
  19. this.traceLRU = new ArrayList<>();
  20. }
  21. public ArrayList<Integer> getTraceLRU(){
  22. return this.traceLRU;
  23. }
  24. private boolean isCheio(){
  25. return this.traceLRU.size() == TAM;
  26. }
  27. private int getIndexFromBloco(int num_bloco){
  28. for(int i = 0; i < this.traceLRU.size(); i++){
  29. if(this.traceLRU.get(i) == num_bloco){
  30. return i;
  31. }
  32. }
  33. return -1;
  34. }
  35. private boolean containsBloco(int num_bloco){
  36. for(int i = 0; i < this.traceLRU.size(); i++){
  37. if(this.traceLRU.get(i) == num_bloco){
  38. return true;
  39. }
  40. }
  41. return false;
  42. }
  43. private void atualizaTraceLRU(int indexDoAcesso){
  44. int bloco = this.traceLRU.get(indexDoAcesso);
  45. for(; indexDoAcesso < this.traceLRU.size()-1; indexDoAcesso++){
  46. this.traceLRU.set(indexDoAcesso,this.traceLRU.get(indexDoAcesso+1));
  47. }
  48. this.traceLRU.set(indexDoAcesso, bloco);
  49. }
  50. private void insereNoFinal(int numBloco){
  51. this.traceLRU.add(numBloco);
  52. }
  53. public void atualizaLRU(int bloco){
  54. //Caso o trace ainda não tenha sido preenchido
  55. if(!isCheio() && containsBloco(bloco)){
  56. this.atualizaTraceLRU(getIndexFromBloco(bloco));
  57. return;
  58. }else if(!isCheio()){
  59. this.insereNoFinal(bloco);
  60. return;
  61. }
  62. //Caso já tenha sido preenchido
  63. int indiceBloco = 0;
  64. for(; indiceBloco < this.traceLRU.size(); indiceBloco++){
  65. if(this.traceLRU.get(indiceBloco) == bloco){
  66. break;
  67. }
  68. }
  69. for(; indiceBloco < this.traceLRU.size()-1;indiceBloco++){
  70. this.traceLRU.set(indiceBloco, this.traceLRU.get(indiceBloco+1));
  71. }
  72. this.traceLRU.set(this.traceLRU.size()-1, bloco);
  73. }
  74. public int getBlocoFromLru(){
  75. if(this.firstTime){
  76. this.firstTime = false;
  77. this.TAM = this.traceLRU.size();
  78. }
  79. if(this.traceLRU.isEmpty()){
  80. return -1;
  81. }
  82. return this.traceLRU.get(0);
  83. }
  84. @Override
  85. public String toString() {
  86. String s = this.traceLRU.toString();
  87. s += "\n";
  88. return s; //To change body of generated methods, choose Tools | Templates.
  89. }
  90. }