修复连接池泄露问题

This commit is contained in:
ascrutae 2016-11-08 21:54:20 +08:00
parent 0cf4683a10
commit 9bbb126917
1 changed files with 17 additions and 40 deletions

View File

@ -2,22 +2,19 @@ package com.a.eye.skywalking.storage.data.index;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class IndexDBConnectorCache {
private static final int MAX_CACHE_SIZE = 5;
private LRUCache<Long, IndexDBConnector> cachedOperators;
private LRUCache cachedOperators;
public IndexDBConnectorCache() {
cachedOperators = new LRUCache<Long, IndexDBConnector>(MAX_CACHE_SIZE);
cachedOperators = new LRUCache(MAX_CACHE_SIZE);
}
public IndexDBConnector get(long timestamp) {
IndexDBConnector connector = cachedOperators.get(timestamp);
IndexDBConnector connector = (IndexDBConnector) cachedOperators.get(timestamp);
if (connector == null) {
connector = new IndexDBConnector(timestamp);
updateCache(timestamp, connector);
@ -29,42 +26,22 @@ public class IndexDBConnectorCache {
cachedOperators.put(timestamp, operator);
}
private static class LRUCache<K, V> {
private final int MAX_CACHE_SIZE;
private final float DEFAULT_LOAD_FACTOR = 0.75f;
private LinkedHashMap<K, V> map;
private ReadWriteLock cacheLock = new ReentrantReadWriteLock();
private void removedCache(IndexDBConnector connector) {
connector.close();
}
private class LRUCache extends LinkedHashMap<Long, IndexDBConnector> {
@Override
protected boolean removeEldestEntry(Map.Entry<Long, IndexDBConnector> eldest) {
boolean isNeedRemove = size() > MAX_CACHE_SIZE;
if (isNeedRemove) {
removedCache(eldest.getValue());
}
return isNeedRemove;
}
public LRUCache(int cacheSize) {
MAX_CACHE_SIZE = cacheSize;
int capacity = (int) Math.ceil(MAX_CACHE_SIZE / DEFAULT_LOAD_FACTOR) + 1;
map = new LinkedHashMap(capacity, DEFAULT_LOAD_FACTOR, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_CACHE_SIZE;
}
};
super((int) Math.ceil(MAX_CACHE_SIZE / 0.75) + 1, 0.75f, true);
}
public void put(K key, V value) {
Lock lock = cacheLock.writeLock();
try {
lock.lock();
map.put(key, value);
} finally {
lock.unlock();
}
}
public V get(K key) {
Lock lock = cacheLock.readLock();
try {
lock.lock();
return map.get(key);
} finally {
lock.unlock();
}
}
}
}