generated from root/miduo_server
99 lines
1.9 KiB
Java
99 lines
1.9 KiB
Java
package util;
|
|
|
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
|
|
|
/**
|
|
* Description: 封装指定类型锁
|
|
* Author: zsx
|
|
* CreateDate: 2020/5/12 15:14
|
|
*/
|
|
public class Lockey implements Comparable<Lockey>{
|
|
|
|
private final int index;
|
|
private final Object key;
|
|
private final int hashcode;
|
|
|
|
private ReentrantReadWriteLock.ReadLock rlock;
|
|
private ReentrantReadWriteLock.WriteLock wlock;
|
|
|
|
Lockey(int id, Object key) {
|
|
this.index = id;
|
|
this.key = key;
|
|
this.hashcode = id ^ (id << 16) ^ key.hashCode();
|
|
}
|
|
|
|
Lockey alloc() {
|
|
ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
|
|
rlock = rwlock.readLock();
|
|
wlock = rwlock.writeLock();
|
|
return this;
|
|
}
|
|
|
|
void rLock() {
|
|
rlock.lock();
|
|
}
|
|
|
|
void wLock() {
|
|
wlock.lock();
|
|
}
|
|
|
|
void rUnlock() {
|
|
rlock.unlock();
|
|
}
|
|
|
|
void wUnlock() {
|
|
wlock.unlock();
|
|
}
|
|
|
|
boolean rTryLock() {
|
|
return rlock.tryLock();
|
|
}
|
|
|
|
boolean wTryLock() {
|
|
return wlock.tryLock();
|
|
}
|
|
|
|
public int getIndex() {
|
|
return index;
|
|
}
|
|
|
|
public Object getKey() {
|
|
return key;
|
|
}
|
|
|
|
public int getHashcode() {
|
|
return hashcode;
|
|
}
|
|
|
|
public ReentrantReadWriteLock.ReadLock getRlock() {
|
|
return rlock;
|
|
}
|
|
|
|
public ReentrantReadWriteLock.WriteLock getWlock() {
|
|
return wlock;
|
|
}
|
|
|
|
@SuppressWarnings("unchecked")
|
|
@Override
|
|
public int compareTo(Lockey o) {
|
|
int x = index - o.index;
|
|
return x != 0 ? x : ((Comparable<Object>) key).compareTo(o.key);
|
|
}
|
|
|
|
@Override
|
|
public int hashCode() {
|
|
return hashcode;
|
|
}
|
|
|
|
@Override
|
|
public boolean equals(Object obj) {
|
|
if (this == obj)
|
|
return true;
|
|
if (obj instanceof Lockey) {
|
|
Lockey o = (Lockey) obj;
|
|
return this.index == o.index && key.equals(o.key);
|
|
}
|
|
return false;
|
|
}
|
|
}
|