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

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

There is a newer version: 10.3.1
Show newest version
package shz.core.lock;

import shz.core.func.VoidConsumer;

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 {
    /**
     * 共享锁
     */
    protected final Lock readLock;
    /**
     * 独占锁
     */
    protected final Lock writeLock;

    public ReadWriteLockHolder() {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        readLock = lock.readLock();
        writeLock = lock.writeLock();
    }

    public final  T applyRead(Supplier supplier) {
        readLock.lock();
        try {
            return supplier.get();
        } finally {
            readLock.unlock();
        }
    }

    public final void acceptRead(VoidConsumer consumer) {
        readLock.lock();
        try {
            consumer.accept();
        } finally {
            readLock.unlock();
        }
    }

    public final  T applyWrite(Supplier supplier) {
        writeLock.lock();
        try {
            return supplier.get();
        } finally {
            writeLock.unlock();
        }
    }

    public final void acceptWrite(VoidConsumer consumer) {
        writeLock.lock();
        try {
            consumer.accept();
        } finally {
            writeLock.unlock();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy