Interface ReadWriteLock<T>
- Type Parameters:
T- the type of lock token | 锁令牌类型
- All Known Implementing Classes:
LocalReadWriteLock, StampedLockAdapter
public interface ReadWriteLock<T>
Read-Write Lock Interface for Concurrent Read Access
读写锁接口 - 支持并发读取访问
Provides separate read and write locks where multiple readers can hold the lock simultaneously, but writers have exclusive access.
提供独立的读锁和写锁,多个读取者可以同时持有锁, 但写入者拥有独占访问权限。
Features | 主要功能:
- Concurrent read access - 并发读取访问
- Exclusive write access - 独占写入访问
- Convenient execute methods - 便捷的执行方法
Usage Examples | 使用示例:
ReadWriteLock<Long> rwLock = OpenLock.readWriteLock();
// Read operation (multiple readers allowed) | 读操作(允许多个读取者)
String data = rwLock.executeRead(() -> loadData());
// Write operation (exclusive access) | 写操作(独占访问)
rwLock.executeWrite(() -> saveData(newData));
// Manual lock management | 手动锁管理
try (var guard = rwLock.readLock().lock()) {
// Read operations | 读操作
}
Performance | 性能特性:
- High read throughput with concurrent readers - 并发读取时高读取吞吐量
- Write operations serialize access - 写操作序列化访问
Security | 安全性:
- Thread-safe: Yes - 线程安全: 是
- Virtual Thread friendly: Yes - 虚拟线程友好: 是
- Since:
- JDK 25, opencode-base-lock V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptiondefault voidexecuteRead(Runnable action) Executes action with read lock held 持有读锁执行操作default <R> RexecuteRead(Supplier<R> supplier) Executes supplier with read lock and returns result 持有读锁执行并返回结果default voidexecuteWrite(Runnable action) Executes action with write lock held 持有写锁执行操作default <R> RexecuteWrite(Supplier<R> supplier) Executes supplier with write lock and returns result 持有写锁执行并返回结果readLock()Gets the read lock for concurrent read access 获取用于并发读取访问的读锁Gets the write lock for exclusive write access 获取用于独占写入访问的写锁
-
Method Details
-
readLock
-
writeLock
-
executeRead
Executes action with read lock held 持有读锁执行操作- Parameters:
action- the action to execute | 要执行的操作
-
executeRead
Executes supplier with read lock and returns result 持有读锁执行并返回结果Examples | 示例:
String data = rwLock.executeRead(() -> readFromCache());- Type Parameters:
R- the result type | 结果类型- Parameters:
supplier- the supplier to execute | 要执行的供应者- Returns:
- the result | 结果
-
executeWrite
Executes action with write lock held 持有写锁执行操作- Parameters:
action- the action to execute | 要执行的操作
-
executeWrite
Executes supplier with write lock and returns result 持有写锁执行并返回结果Examples | 示例:
String result = rwLock.executeWrite(() -> updateAndReturn(newData));- Type Parameters:
R- the result type | 结果类型- Parameters:
supplier- the supplier to execute | 要执行的供应者- Returns:
- the result | 结果
-