import java.util.*;
import java.io.*;

class myFile {
  long lastmodified;
  String contents;

  public myFile(long last, String data) {
    lastmodified=last;
    contents=data;
  }
  public long getLastModified() {
    return lastmodified;
  }
  public String getContents() {
    return contents;
  }
}

public class MRUCache {

  Map cache;
  LinkedList mrulist;
  int cachesize;

  public MRUCache(int max) {
    cache = new HashMap();
    mrulist= new LinkedList();
    cachesize=max;
  }

  public String getFile(String fname) {
    if(!cache.containsKey(fname)) {
      synchronized(cache) {
        if(mrulist.size() >=cachesize) {
          cache.remove(mrulist.getLast());
          mrulist.removeLast();
        }
        cache.put(fname, readFile(fname));
        mrulist.addFirst(fname);
      }
    } else {
      if((new File(fname).lastModified())>
        ((myFile)cache.get(fname)).getLastModified()) {
          synchronized(cache) {
            cache.put(fname, readFile(fname));
          }
       }
       synchronized(cache) {
         mrulist.remove(fname);
         mrulist.addFirst(fname);
       }
    }
       return ((myFile)cache.get(fname)).getContents();
  }

  public myFile readFile(String name) {
    File f = new File(name);
    StringBuffer filecontents= new StringBuffer();

    try {
      BufferedReader br=new BufferedReader(new FileReader(f));
      String line;

      while((line =br.readLine()) != null) {
        filecontents.append(line);
      }
    } catch (FileNotFoundException fnfe){
      return (null);
    } catch ( IOException ioe) {
                return (null);
    }
      return (new myFile(f.lastModified(), filecontents.toString()));
  }

  public void printList() {
    for(int i=0; i<mrulist.size(); i++) {
      System.out.println("item "+i+"="+mrulist.get(i));
    }
  }

  public static void main(String args[]) {
    MRUCache h1=new MRUCache(10);
    for(int i=1; i<=20; i++) {
      h1.getFile("data"+File.separatorChar+i);
    }
      h1.printList();
  }
}
