zk中ReferenceCountedACLCache

左心房为你撑大大i 提交于 2019-11-30 18:18:25

作用:完成LIst<ACL>与Long互相转换,DataNode中acl是一个Long值,并不是ACL列表

空间复杂:内部类AtomicLongWithEquals

 

属性:

//日志信息
private static final Logger LOG = LoggerFactory.getLogger(ReferenceCountedACLCache.class);
// long ACL 列表对应关系
final Map<Long, List<ACL>> longKeyMap = new HashMap<Long, List<ACL>>();
//  ACL 列表 long对应关系
final Map<List<ACL>, Long> aclKeyMap = new HashMap<List<ACL>, Long>();
final Map<Long, AtomicLongWithEquals> referenceCounter = new HashMap<Long, AtomicLongWithEquals>();
private static final long OPEN_UNSAFE_ACL_ID = -1L;

/**
 * these are the number of acls that we have in the datatree
 */
long aclIndex = 0;

 

方法:

记录引用次数

private static class AtomicLongWithEquals extends AtomicLong {

    private static final long serialVersionUID = 3355155896813725462L;

    public AtomicLongWithEquals(long i) {
        super(i);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        return equals((AtomicLongWithEquals) o);
    }

    public boolean equals(AtomicLongWithEquals that) {
        return get() == that.get();
    }

    @Override
    public int hashCode() {
        return 31 * Long.valueOf(get()).hashCode();
    }

}

添加使用
public synchronized void addUsage(Long acl) {
    if (acl == OPEN_UNSAFE_ACL_ID) {
        return;
    }

    if (!longKeyMap.containsKey(acl)) {
        LOG.info("Ignoring acl " + acl + " as it does not exist in the cache");
        return;
    }

    AtomicLong count = referenceCounter.get(acl);
    if (count == null) {
        referenceCounter.put(acl, new AtomicLongWithEquals(1));
    } else {
        count.incrementAndGet();
    }
}

//移除引用
public synchronized void removeUsage(Long acl) {
    if (acl == OPEN_UNSAFE_ACL_ID) {
        return;
    }

    if (!longKeyMap.containsKey(acl)) {
        LOG.info("Ignoring acl " + acl + " as it does not exist in the cache");
        return;
    }

    long newCount = referenceCounter.get(acl).decrementAndGet();
    if (newCount <= 0) {
        referenceCounter.remove(acl);
        aclKeyMap.remove(longKeyMap.get(acl));
        longKeyMap.remove(acl);
    }
}


//如果引用计数值小于0,则移除相关信息
public synchronized void purgeUnused() {
    Iterator<Map.Entry<Long, AtomicLongWithEquals>> refCountIter = referenceCounter.entrySet().iterator();
    while (refCountIter.hasNext()) {
        Map.Entry<Long, AtomicLongWithEquals> entry = refCountIter.next();
        if (entry.getValue().get() <= 0) {
            Long acl = entry.getKey();
            aclKeyMap.remove(longKeyMap.get(acl));
            longKeyMap.remove(acl);
            refCountIter.remove();
        }
    }
}

 

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!