shz.core.lock.ReadWriteLockHolder Maven / Gradle / Ivy
package shz.core.lock;
import shz.core.PRException;
import shz.core.msg.ClientFailure;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
public class ReadWriteLockHolder implements LockHolder {
/**
* 共享锁
*/
protected final Lock readLock;
/**
* 独占锁
*/
protected final Lock writeLock;
public ReadWriteLockHolder() {
ReadWriteLock lock = new ReentrantReadWriteLock();
readLock = lock.readLock();
writeLock = lock.writeLock();
}
@Override
public final R applyRead(Supplier extends R> supplier, long time, TimeUnit unit) {
if (time > 0L) {
try {
if (readLock.tryLock(time, unit)) {
try {
return supplier.get();
} finally {
readLock.unlock();
}
}
} catch (InterruptedException e) {
throw PRException.of(e);
}
throw PRException.of(ClientFailure.CLIENT_TIMEOUT);
}
readLock.lock();
try {
return supplier.get();
} finally {
readLock.unlock();
}
}
@Override
public final R applyRead(Supplier extends R> supplier) {
return LockHolder.super.applyRead(supplier);
}
@Override
public final void acceptRead(Runnable runnable, long time, TimeUnit unit) {
if (time > 0L) {
try {
if (readLock.tryLock(time, unit)) {
try {
runnable.run();
} finally {
readLock.unlock();
}
return;
}
} catch (InterruptedException e) {
throw PRException.of(e);
}
throw PRException.of(ClientFailure.CLIENT_TIMEOUT);
}
readLock.lock();
try {
runnable.run();
} finally {
readLock.unlock();
}
}
@Override
public final void acceptRead(Runnable runnable) {
LockHolder.super.acceptRead(runnable);
}
@Override
public final R applyWrite(Supplier extends R> supplier, long time, TimeUnit unit) {
if (time > 0L) {
try {
if (writeLock.tryLock(time, unit)) {
try {
return supplier.get();
} finally {
writeLock.unlock();
}
}
} catch (InterruptedException e) {
throw PRException.of(e);
}
throw PRException.of(ClientFailure.CLIENT_TIMEOUT);
}
writeLock.lock();
try {
return supplier.get();
} finally {
writeLock.unlock();
}
}
@Override
public final R applyWrite(Supplier extends R> supplier) {
return LockHolder.super.applyWrite(supplier);
}
@Override
public final void acceptWrite(Runnable runnable, long time, TimeUnit unit) {
if (time > 0L) {
try {
if (writeLock.tryLock(time, unit)) {
try {
runnable.run();
} finally {
writeLock.unlock();
}
return;
}
} catch (InterruptedException e) {
throw PRException.of(e);
}
throw PRException.of(ClientFailure.CLIENT_TIMEOUT);
}
writeLock.lock();
try {
runnable.run();
} finally {
writeLock.unlock();
}
}
@Override
public final void acceptWrite(Runnable runnable) {
LockHolder.super.acceptWrite(runnable);
}
}