堆外內存及其在 RxCache 中的使用

RxCache

RxCache 是一款支持 Java 和 Android 的 Local Cache 。目前,支持堆內存、堆外內存(off-heap memory)、磁盤緩存。

github地址:https://github.com/fengzhizi715/RxCache

堆外內存(off-heap memory)

對象可以存儲在 堆內存、堆外內存、磁盤緩存甚至是分佈式緩存。

在 Java 中,與堆外內存相對的是堆內存。堆內存遵守 JVM 的內存管理機制,而堆外內存不受到此限制,它由操作系統進行管理。

堆外內存和堆內存有明顯的區別,或者說有相反的應用場景。

堆外內存更適合:

  • 存儲生命週期長的對象
  • 可以在進程間可以共享,減少 JVM 間的對象複製,使得 JVM 的分割部署更容易實現。
  • 本地緩存,減少磁盤緩存或者分佈式緩存的響應時間。

RxCache 中使用的堆外內存

首先,創建一個 DirectBufferConverter ,用於將對象和 ByteBuffer 相互轉換,以及對象和byte數組相互轉換。其中,ByteBuffer.allocteDirect(capability) 用於分配堆外內存。Cleaner 是自己定義的一個類,用於釋放 DirectByteBuffer。具體代碼可以查看:https://github.com/fengzhizi715/RxCache/blob/master/offheap/src/main/java/com/safframework/rxcache/offheap/converter/Cleaner.java

public abstract class DirectBufferConverter<V> {

    public void dispose(ByteBuffer direct) {

        Cleaner.clean(direct);
    }

    public ByteBuffer to(V from) {
        if(from == null) return null;

        byte[] bytes = toBytes(from);
        ByteBuffer.wrap(bytes);
        ByteBuffer bf = ByteBuffer.allocateDirect(bytes.length);
        bf.put(bytes);
        bf.flip();
        return bf;
    }

    abstract public byte[] toBytes(V value);

    abstract public V toObject(byte[] value);

    public V from(ByteBuffer to) {
        if(to == null) return null;

        byte[] bs = new byte[to.capacity()];
        to.get(bs);
        to.flip();
        return toObject(bs);
    }

}

接下來,定義一個 ConcurrentDirectHashMap<K, V> 實現Map接口。它是一個範性,支持將 V 轉換成 ByteBuffer 類型,存儲到 ConcurrentDirectHashMap 的 map 中。

public abstract class ConcurrentDirectHashMap<K, V> implements Map<K, V> {

    final private Map<K, ByteBuffer> map;

    private final DirectBufferConverter<V> converter = new DirectBufferConverter<V>() {

        @Override
        public byte[] toBytes(V value) {
            return convertObjectToBytes(value);
        }

        @Override
        public V toObject(byte[] value) {
            return convertBytesToObject(value);
        }
    };

    ConcurrentDirectHashMap() {

        map = new ConcurrentHashMap<>();
    }

    ConcurrentDirectHashMap(Map<K, V> m) {

        map = new ConcurrentHashMap<>();

        for (Entry<K, V> entry : m.entrySet()) {
            K key = entry.getKey();
            ByteBuffer val = converter.to(entry.getValue());
            map.put(key, val);
        }
    }

    protected abstract byte[] convertObjectToBytes(V value);

    protected abstract V convertBytesToObject(byte[] value);

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    @Override
    public V get(Object key) {
        final ByteBuffer byteBuffer = map.get(key);
        return converter.from(byteBuffer);
    }

    @Override
    public V put(K key, V value) {
        final ByteBuffer byteBuffer = map.put(key, converter.to(value));
        converter.dispose(byteBuffer);
        return converter.from(byteBuffer);
    }

    @Override
    public V remove(Object key) {
        final ByteBuffer byteBuffer = map.remove(key);
        final V value = converter.from(byteBuffer);
        converter.dispose(byteBuffer);
        return value;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
            ByteBuffer byteBuffer = converter.to(entry.getValue());
            map.put(entry.getKey(), byteBuffer);
        }
    }

    @Override
    public void clear() {
        final Set<K> keys = map.keySet();

        for (K key : keys) {
            map.remove(key);
        }
    }

    @Override
    public Set<K> keySet() {
        return map.keySet();
    }

    @Override
    public Collection<V> values() {
        Collection<V> values = new ArrayList<>();

        for (ByteBuffer byteBuffer : map.values())
        {
            V value = converter.from(byteBuffer);
            values.add(value);
        }
        return values;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Entry<K, V>> entries = new HashSet<>();

        for (Entry<K, ByteBuffer> entry : map.entrySet()) {
            K key = entry.getKey();
            V value = converter.from(entry.getValue());

            entries.add(new Entry<K, V>() {
                @Override
                public K getKey() {
                    return key;
                }

                @Override
                public V getValue() {
                    return value;
                }

                @Override
                public V setValue(V v) {
                    return null;
                }
            });
        }

        return entries;
    }

    @Override
    public boolean containsValue(Object value) {

        for (ByteBuffer v : map.values()) {
            if (v.equals(value)) {
                return true;
            }
        }
        return false;
    }
}

創建 ConcurrentStringObjectDirectHashMap,它的 K 是 String 類型,V 是任意的 Object 對象。其中,序列化和反序列化採用《Java 字節的常用封裝》提到的 bytekit

public class ConcurrentStringObjectDirectHashMap extends ConcurrentDirectHashMap<String,Object> {

    @Override
    protected byte[] convertObjectToBytes(Object value) {

        return Bytes.serialize(value);
    }

    @Override
    protected Object convertBytesToObject(byte[] value) {

        return Bytes.deserialize(value);
    }
}

基於 FIFO 以及堆外內存來實現 Memory 級別的緩存。

public class DirectBufferMemoryImpl extends AbstractMemoryImpl {

    private ConcurrentStringObjectDirectHashMap cache;
    private List<String> keys;

    public DirectBufferMemoryImpl(long maxSize) {

        super(maxSize);
        cache = new ConcurrentStringObjectDirectHashMap();
        this.keys = new LinkedList<>();
    }

    @Override
    public <T> Record<T> getIfPresent(String key) {

        T result = null;

        if(expireTimeMap.get(key)!=null) {

            if (expireTimeMap.get(key)<0) { // 緩存的數據從不過期

                result = (T) cache.get(key);
            } else {

                if (timestampMap.get(key) + expireTimeMap.get(key) > System.currentTimeMillis()) {  // 緩存的數據還沒有過期

                    result = (T) cache.get(key);
                } else {                     // 緩存的數據已經過期

                    evict(key);
                }
            }
        }

        return result != null ? new Record<>(Source.MEMORY,key, result, timestampMap.get(key),expireTimeMap.get(key)) : null;
    }

    @Override
    public <T> void put(String key, T value) {

        put(key,value, Constant.NEVER_EXPIRE);
    }

    @Override
    public <T> void put(String key, T value, long expireTime) {

        if (keySet().size()<maxSize) { // 緩存還有空間

            saveValue(key,value,expireTime);
        } else {                       // 緩存空間不足,需要刪除一個

            if (containsKey(key)) {

                keys.remove(key);

                saveValue(key,value,expireTime);
            } else {

                String oldKey = keys.get(0); // 最早緩存的key
                evict(oldKey);               // 刪除最早緩存的數據 FIFO算法

                saveValue(key,value,expireTime);
            }
        }
    }

    private <T> void saveValue(String key, T value, long expireTime) {

        cache.put(key,value);
        timestampMap.put(key,System.currentTimeMillis());
        expireTimeMap.put(key,expireTime);
        keys.add(key);
    }

    @Override
    public Set<String> keySet() {

        return cache.keySet();
    }

    @Override
    public boolean containsKey(String key) {

        return cache.containsKey(key);
    }

    @Override
    public void evict(String key) {

        cache.remove(key);
        timestampMap.remove(key);
        expireTimeMap.remove(key);
        keys.remove(key);
    }

    @Override
    public void evictAll() {

        cache.clear();
        timestampMap.clear();
        expireTimeMap.clear();
        keys.clear();
    }
}

到了這裏,已經完成了堆外內存在 RxCache 中的封裝。其實,已經有很多緩存框架都支持堆外內存,例如 Ehcache、MapDB 等。RxCache 目前已經有了 MapDB 的模塊。

總結

RxCache 是一款 Local Cache,它已經應用到我們項目中,也在我個人的爬蟲框架 NetDiscovery 中使用。未來,它會作爲一個成熟的組件,不斷運用到公司和個人的其他項目中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章