package com.qmth.jkserver.common;

import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;

/**
 * 内存锁
 * @author tianjun
 *
 */
@Component
public class MemoryLock {
	
    private static ConcurrentHashMap<String, String> stringCache = new ConcurrentHashMap<String, String>();// 缓存
    private static ConcurrentHashMap<String, Long> timeCache = new ConcurrentHashMap<String, Long>();
	
    /**
     * 加锁
     * @param key 缓存key
     * @param value 缓存value 
     * @param timeout 缓存过期时间 单位毫秒
     */
	public boolean lock(String key, String value,int timeout) {
		if(stringCache.get(key)==null){
			stringCache.put(key, value);
			timeCache.put(key, System.currentTimeMillis()+ Long.valueOf(timeout+""));
			return true;
		}
		else{
			if(timeCache.get(key).longValue() < System.currentTimeMillis()){
				//锁已经过期
				stringCache.put(key, value);
				timeCache.put(key, System.currentTimeMillis()+ Long.valueOf(timeout+""));
				return true;
			}
			else{
				return false;
			}
		}
	}

	public void unlock(String key, String value) {
		stringCache.remove(key);
		timeCache.remove(key);
	}


}
