1. 程式人生 > 實用技巧 >【Mybatis】LRU緩衝的實現

【Mybatis】LRU緩衝的實現

LRU (least recently used) 即“最近最少使用”緩衝淘汰演算法。
Mybatis 的 LRUCache 是利用 java 的基礎工具包 LinkedHashMap 特性二次開發完成。

Cache 介面定義

public interface Cache {

  /**
   * 緩衝 ID
   */
  String getId();

  /**
   * 儲存資料
   */
  void putObject(Object key, Object value);

  /**
   * 獲取資料
   */
  Object getObject(Object key);

  /**
   * 刪除資料
   */
  Object removeObject(Object key);

  /**
   * 清空緩衝
   */
  void clear();

  /**
   * 獲取緩衝大小
   */
  int getSize();
  
  ReadWriteLock getReadWriteLock();
}

LRUCache 實現類

LRUCache 實現 Cache 介面

package org.apache.ibatis.cache.decorators;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import org.apache.ibatis.cache.Cache;

/**
 * Lru (least recently used) cache decorator
 */
public class LruCache implements Cache {

  private final Cache delegate;
  private Map<Object, Object> keyMap;
  private Object eldestKey;

  public LruCache(Cache delegate) {
    this.delegate = delegate;
    setSize(1024);
  }

  @Override
  public String getId() {
    return delegate.getId();
  }

  @Override
  public int getSize() {
    return delegate.getSize();
  }

  public void setSize(final int size) {
    keyMap = new LinkedHashMap<Object, Object>(size, .75F, true) {
      private static final long serialVersionUID = 4267176411845948333L;

      @Override
      protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {
        boolean tooBig = size() > size;
        if (tooBig) {
          eldestKey = eldest.getKey();
        }
        return tooBig;
      }
    };
  }

  @Override
  public void putObject(Object key, Object value) {
    delegate.putObject(key, value);
    cycleKeyList(key);
  }

  @Override
  public Object getObject(Object key) {
    keyMap.get(key); //touch
    return delegate.getObject(key);
  }

  @Override
  public Object removeObject(Object key) {
    return delegate.removeObject(key);
  }

  @Override
  public void clear() {
    delegate.clear();
    keyMap.clear();
  }

  @Override
  public ReadWriteLock getReadWriteLock() {
    return null;
  }

  private void cycleKeyList(Object key) {
    keyMap.put(key, key);
    if (eldestKey != null) {
      delegate.removeObject(eldestKey);
      eldestKey = null;
    }
  }
}