All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.lock.ReentrantLockHolder Maven / Gradle / Ivy

There is a newer version: 2024.0.2
Show newest version
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 supplier, long time, TimeUnit unit) {
        return applyWrite(supplier, time, unit);
    }

    @Override
    public final  R applyRead(Supplier 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 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 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);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy