集册 Java实例教程 并发LRU缓存

并发LRU缓存

欢马劈雪     最近更新时间:2020-01-02 10:19:05

626
并发LRU缓存
/*
n o w    j a v a  . c o m
*/

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.ConcurrentLinkedQueue;


class LRU<Key, Value> {

  private int size;

  private ConcurrentLinkedQueue<Key> linkedQueue;

  private ConcurrentHashMap<Key, Value> hashMap;


  public LRU(final int size) {

    this.size = size;

    this.linkedQueue = new ConcurrentLinkedQueue<Key>();

    this.hashMap = new ConcurrentHashMap<Key, Value>(size);

  }


  /**

   * Return the Value corresponding to the given Key in the map. return null if

   * key not found.

   * 

   * @param key

   *          - Key

   * @return value - Value

   *//** 来 自 时   代     Java  公  众  号 - nowjava.com**/

  public Value get(Key key) {

    Value value = hashMap.get(key);

    if (value != null) {

      linkedQueue.remove(key);

      linkedQueue.add(key);

    }

    return value;

  }


  /**

   * Add new Key, Value pair to our Map and Queue. If the Key already exists, move

   * it at the beginning of the queue.

   * 

   * @param key

   *          - Key

   * @param value

   *          - Value

   */

  public synchronized void put(final Key key, final Value value) {

    if (hashMap.containsKey(key)) {

      linkedQueue.remove(key);

    }


    while (linkedQueue.size() >= size) {

      Key oldestKey = linkedQueue.poll();

      if (oldestKey != null) {

        hashMap.remove(oldestKey);

      }


      linkedQueue.add(key);

      hashMap.put(key, value);

    }

  }

}


public class Main{

  public static void main(String arg[]) {


    LRU lru = new LRU(3);


    lru.put(1, 1);

    lru.put(2, 2);

   
展开阅读全文