public class User implements Serializable{
public static final String USER_LOCK = "User_Lock_";
/**
* 获取对象锁,每个用户在缓存中有一个锁
*
* @param userId
* 用户id
* @return ReentrantLock 锁
*/
private static ReentrantLock getLock(long userId) {
ReentrantLock lock = (ReentrantLock) Cache.get(USER_LOCK + userId);
if (lock == null) {
synchronized (User.class) { // 单例,一个用户,一个锁
lock = (ReentrantLock) Cache.get(USER_LOCK + userId);
if (lock == null) {
lock = new ReentrantLock();
Cache.set(USER_LOCK + userId, lock);
}
}
}
return lock;
}
/**
* 加锁
*
* @param userId
*/
public static void addLock(long userId) {
getLock(userId).lock();
}
/**
* 解锁
*
* @param userId
*/
public static void deleteLock(long userId) {
ReentrantLock lock = getLock(userId);
if (lock == null) {
return;
}
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
/**
* 清除锁缓存
*/
public static void cleanCacheLock(String userId) {
ReentrantLock lock = (ReentrantLock) Cache.get(USER_LOCK + userId);
if (lock == null) {
return;
}
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
if (!lock.hasQueuedThreads()) {
Cache.delete(USER_LOCK + userId);
}
}
public void updateSignWithLock(long userId) {
if (userId == 0) {
Logger.info("加锁:userId等于0");
return ;
}
User.addLock(userId); //加锁
try {
doUser();
} finally {
User.deleteLock(userId); //解锁
}
}
}
对象锁
最新推荐文章于 2023-06-13 17:44:26 发布