Wednesday 25 January 2017

Least Recently Used(LRU) algorithm for demand paging implementation in Java


public class LRU { private String input; private int frameSize; private int falutCount=0; private int[] timeCount; private String[] frameStack; /** * * @param commaSepratedPages * Page String will be like '7,0,1,2,0,3,0' * @param frameSize * Frame Size that can hold Pages. */ public LRU(String commaSepratedPages,int frameSize){ this.frameSize=frameSize; timeCount=new int[frameSize]; frameStack=new String[frameSize]; input=commaSepratedPages; } /** * Number of page faults with given Frame Size and Input. * @return */ public int getPageFaults(){ falutCount=0; String[] pages=input.split(","); System.out.println("Pages :\n "+input); System.out.println("Fault Pages "); for(String page:pages){ updateStack(page); } return falutCount; } private void updateStack(String page){ boolean isFaultOccured=true; int matchIndex=0; for(int i=0;i<frameSize;i++){ if(page.equals(frameStack[i])){ timeCount[i]=0; matchIndex=i; isFaultOccured=false; break; } } if(isFaultOccured){ System.out.print(page+" "); falutCount++; matchIndex=getLeastRecentlyUsedIndex(); frameStack[matchIndex]=page; timeCount[matchIndex]=0; } upadteUsedTime(matchIndex); } private void upadteUsedTime(int pageHitIndex){ for(int i=0;i<frameSize;i++){ if(i!=pageHitIndex){ timeCount[i]++; } } } private int getLeastRecentlyUsedIndex(){ int index=0; int time=0; for(int i=0;i<frameSize;i++){ if(timeCount[i]>time){ time=timeCount[i]; index=i; } } return index; } }

No comments:

Post a Comment