memory-and-process-scheduler

git clone git://git.codymlewis.com/memory-and-process-scheduler.git
Log | Files | Refs | README

LRU.java (1744B)


      1 import java.util.LinkedList;
      2 import java.util.ArrayList;
      3 import java.util.Collections;
      4 
      5 public class LRU extends FrameBuffer {
      6     private class LRUPage implements Comparable<LRUPage> {
      7         Integer time;
      8         int id;
      9 
     10         public LRUPage(int id, int time) {
     11             this.id = id;
     12             this.time = time;
     13         }
     14 
     15         public void use(int time) {
     16             this.time = time;
     17         }
     18 
     19         public int getId() {
     20             return id;
     21         }
     22 
     23         public Integer getTime() {
     24             return time;
     25         }
     26 
     27         public int compareTo(LRUPage other) {
     28             return time.compareTo(other.getTime());
     29         }
     30 
     31         public String toString() {
     32             return String.format("{id: %d, time: %d}", id, time);
     33         }
     34     }
     35 
     36     private ArrayList<LRUPage> lrubuffer;
     37     private int counter; // Counts time relativistically
     38 
     39 
     40     public LRU(int totalFrames) {
     41         super(totalFrames);
     42         lrubuffer = new ArrayList<>();
     43         counter = 0;
     44     }
     45 
     46     @Override
     47     public void replace(Integer newPage) {
     48         int replaceFrameNum;
     49         if (lrubuffer.size() == totalFrames) {
     50             replaceFrameNum = loadedPages.get(Collections.min(lrubuffer).getId());
     51             loadedPages.remove(buffer.get(replaceFrameNum));
     52             lrubuffer.set(replaceFrameNum, new LRUPage(newPage, counter));
     53         } else {
     54             replaceFrameNum = lrubuffer.size();
     55             lrubuffer.add(new LRUPage(newPage, counter));
     56         }
     57         buffer.set(replaceFrameNum, newPage);
     58         loadedPages.put(buffer.get(replaceFrameNum), replaceFrameNum);
     59     }
     60 
     61     @Override
     62     public void use(int page) {
     63         counter++;
     64         lrubuffer.get(loadedPages.get(page)).use(counter);
     65     }
     66 }