package com.qmth.sop.common.lock;

import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 内存锁
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2023/7/17
 */
@Component
public class MemoryLock {
    private static ConcurrentHashMap<String, Object> stringCache = new ConcurrentHashMap<>();// 缓存
    private static ConcurrentHashMap<String, Long> timeCache = new ConcurrentHashMap<>();

    /**
     * 加锁
     *
     * @param key
     * @param value
     * @param timeout
     * @return
     */
    public boolean lock(String key, Object value, Long timeout) {
        if (Objects.isNull(stringCache.get(key))) {
            stringCache.put(key, value);
            timeCache.put(key, System.currentTimeMillis() + timeout);
            return true;
        } else {
            if (timeCache.get(key).longValue() < System.currentTimeMillis()) {
                //锁已经过期
                stringCache.put(key, value);
                timeCache.put(key, System.currentTimeMillis() + timeout);
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 解锁
     *
     * @param key
     */
    public void unlock(String key) {
        stringCache.remove(key);
        timeCache.remove(key);
    }
}
