LRU.java 2.8 KB

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