为什么 reddison ExpirationEntry 使用 LinkedHashMap 来保存 Thr​​ead?

问题描述

Reddison watchDog 策略使用 timerTask 在设置锁成功的同时增加密钥过期时间

private void renewExpiration() {
    ExpirationEntry ee = EXPIRATION_renewal_MAP.get(getEntryName());
    if (ee == null) {
        return;
    }
    
    Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            ExpirationEntry ent = EXPIRATION_renewal_MAP.get(getEntryName());
            if (ent == null) {
                return;
            }
            Long threadId = ent.getFirstThreadId();
            if (threadId == null) {
                return;
            }
            
            RFuture<Boolean> future = renewExpirationAsync(threadId);
            ......
   }

}

首先使用 entryName获取 ExpirationEntry 对象。对于同一个entryName,其他线程因为locked而无法获取key(ps:同一个线程可以获取和counter++),那么如果只有一个线程,为什么要用LinkedHashMap来保存线程呢?

公共静态类 ExpirationEntry {

    private final Map<Long,Integer> threadIds = new LinkedHashMap<>();
    private volatile Timeout timeout;

    public ExpirationEntry() {
        super();
    }

    public synchronized void addThreadId(long threadId) {
        Integer counter = threadIds.get(threadId);
        if (counter == null) {
            counter = 1;
        } else {
            counter++;
        }
        threadIds.put(threadId,counter);
    }

}

也许就是这样:

public static class ExpirationEntry {
    private volatile Timeout timeout;
    private Long threadId;
    private int counter;

    public synchronized void addThread(Long threadId) {
        if (this.threadId.equals(threadId)) {
            counter ++;
        }
    }
}

我将不胜感激,谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)