mirror of
https://github.com/LamGC/ContentGrabbingJi.git
synced 2025-07-03 13:57:26 +00:00
[Add] LockerMap, Locker 增加Locker锁对象和LockerMap锁对象存储;
[Change] CacheStoreCentral 将synchronized所使用的的锁对象由String(常量池)转换成Locker<K>以尝试减少内存占用;
This commit is contained in:
64
src/main/java/net/lamgc/cgj/util/Locker.java
Normal file
64
src/main/java/net/lamgc/cgj/util/Locker.java
Normal file
@ -0,0 +1,64 @@
|
||||
package net.lamgc.cgj.util;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public final class Locker<K> {
|
||||
|
||||
private final LockerMap<K> fromMap;
|
||||
|
||||
private final K key;
|
||||
|
||||
private final boolean autoDestroy;
|
||||
|
||||
private final AtomicInteger lockCount = new AtomicInteger(0);
|
||||
|
||||
/**
|
||||
* 构造一个锁对象
|
||||
* @param map 所属LockerMap
|
||||
* @param key 所属Key
|
||||
*/
|
||||
Locker(LockerMap<K> map, K key, boolean autoDestroy) {
|
||||
this.fromMap = map;
|
||||
this.key = key;
|
||||
this.autoDestroy = autoDestroy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上锁
|
||||
*/
|
||||
public void lock() {
|
||||
lockCount.incrementAndGet();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解锁
|
||||
*/
|
||||
public void unlock() {
|
||||
int newValue = lockCount.decrementAndGet();
|
||||
if(newValue <= 0 && autoDestroy) {
|
||||
destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取锁对象所属Key
|
||||
*/
|
||||
public K getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁锁对象
|
||||
*/
|
||||
public void destroy() {
|
||||
fromMap.destroyLocker(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Locker{" +
|
||||
"fromMap=" + fromMap +
|
||||
", key=" + key +
|
||||
'}';
|
||||
}
|
||||
}
|
31
src/main/java/net/lamgc/cgj/util/LockerMap.java
Normal file
31
src/main/java/net/lamgc/cgj/util/LockerMap.java
Normal file
@ -0,0 +1,31 @@
|
||||
package net.lamgc.cgj.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class LockerMap<K> {
|
||||
|
||||
private final HashMap<K, Locker<K>> lockerHashMap = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 创建锁
|
||||
* @param key Key
|
||||
* @return 如果Key所属锁存在, 则返回对应锁, 否则返回新锁
|
||||
*/
|
||||
public Locker<K> createLocker(K key, boolean autoDestroy) {
|
||||
if(lockerHashMap.containsKey(key)) {
|
||||
return lockerHashMap.get(key);
|
||||
}
|
||||
Locker<K> newLocker = new Locker<>(this, key, autoDestroy);
|
||||
lockerHashMap.put(key, newLocker);
|
||||
return newLocker;
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁锁
|
||||
* @param locker 锁对象
|
||||
*/
|
||||
public void destroyLocker(Locker<K> locker) {
|
||||
lockerHashMap.remove(locker.getKey());
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user