Implementation of LRU algorithm in Java

Time:2021-2-26

Recently, I met Alibaba’s outsourcing company, but I have to knock the code online. That’s a tension. The topic is to implement a cache of LRU algorithm. Outsourcing is so demanding, eh. Fortunately, LRU is a topic assigned by my university teacher. Of course, I implemented it in C language. The principle of the algorithm is clear, but my mind was blank during the interview. Fortunately, while knocking code, while thinking, it slowly came to mind, the following is my code. For reference only

/**
 *Design and build a "least recently used" LRU cache, which will delete the least recently used items.
 *The cache should be mapped from a key to a value (allowing you to insert and retrieve values for a particular key), and the maximum capacity should be specified at initialization time.
 *When the cache is full, it should delete the least recently used items.
 *Consider the security and performance of multithreading operation.
 */
public class LRUCache{

  private int maxSize;
  
  /**
  *Store cache data
  */
  private ConcurrentHashMap map = new ConcurrentHashMap<>();
  
  /**
  **Store cache key list
  */
  private LinkedList list;
  
  LRUCache(){
  }

  LRUCache(int maxSize){
      this.maxSize = maxSize;
    this.list = new LinkedList<>(maxSize);
  }
  

  /**
  *@ param key cache key
    @Return cache value
  */
  synchronized Object getVal(String key){
    //1. Get data from map
    Object obj = map.get(key);
    
    //2. Put the key at the end of the list
    if(obj != null){
        addOrRefreshKey(key);
    }
  }
  
  synchronized void putVal(String key,Object val){
      //1. Set Val to map
    
    //2. Put the key at the end of the list
    
      //3. Need to judge whether list.size ()>maxSize。 If it is full, delete the data in the header (the least recently used) and then perform steps 1-2
  }
  
  
  /**
  *Add or refresh key
  */
  private void addOrRefreshKey(String key){
      this.list.remove (key); // delete it first
    this.list.add (key); // then add this to ensure that the key is placed at the end of the list
  }

  
  
  
}