shz.core.lock.ReentrantLockHolder 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.ReentrantLock;
import java.util.function.Supplier;
public class ReentrantLockHolder implements LockHolder {
protected final Lock lock = new ReentrantLock();
@Override
public final R applyRead(Supplier extends R> supplier, long time, TimeUnit unit) {
return applyWrite(supplier, time, unit);
}
@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) {
acceptWrite(runnable, time, unit);
}
@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 (lock.tryLock(time, unit)) {
try {
return supplier.get();
} finally {
lock.unlock();
}
}
} catch (InterruptedException e) {
throw PRException.of(e);
}
throw PRException.of(ClientFailure.CLIENT_TIMEOUT);
}
lock.lock();
try {
return supplier.get();
} finally {
lock.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 (lock.tryLock(time, unit)) {
try {
runnable.run();
} finally {
lock.unlock();
}
return;
}
} catch (InterruptedException e) {
throw PRException.of(e);
}
throw PRException.of(ClientFailure.CLIENT_TIMEOUT);
}
lock.lock();
try {
runnable.run();
} finally {
lock.unlock();
}
}
@Override
public final void acceptWrite(Runnable runnable) {
LockHolder.super.acceptWrite(runnable);
}
}