StampedLock使用示例

StampedLock使用示例

StampedLock是对读写锁ReentrantReadWriteLock的优化,包括读写锁之间的转换及更加细粒度的并发控制等。

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.stampedLockInstance")
public class StampedLockInstance {
    
    public static void main(String[] args) {
        DataContainerStamped stamped = new DataContainerStamped(1);
        new Thread(() -> {
           try {
               stamped.read(1000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
        }, "t1").start();
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        new Thread(()->{
            stamped.write(1000);
        }, "t2").start();
    }
    
    @Slf4j(topic = "c.dataContainerStamped")
    private static class DataContainerStamped{
        private int data;
        private final StampedLock lock = new StampedLock();
        
        DataContainerStamped(int data) {
            this.data = data;
        }
        
        public int read(int readTime) throws InterruptedException {
            //乐观读 - 不支持条件变量、不可重入
            long stamp = lock.tryOptimisticRead();
            log.info("optimistic read locking... {}", stamp);
            Thread.sleep(readTime);
            //验戳 - 乐观锁
            if (lock.validate(stamp)) {
                log.info("read finish... {}", stamp);
                return data;
            }
            
            //锁升级成读锁
            log.info("updating to read lock... {}", stamp);
            try {
                stamp = lock.readLock();
                log.info("read lock {}", stamp);
                Thread.sleep(readTime);
                log.info("read finish... {}", stamp);
                return data;
            } finally {
                log.info("read unlock {}", stamp);
                lock.unlockRead(stamp);
            }
        }
        
        public void write(int data) {
            long stamp = lock.writeLock();
            log.info("write lock {}", stamp);
            try {
                Thread.sleep(2000);
                this.data = data;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                log.info("write unlock {}", stamp);
                lock.unlockWrite(stamp);
            }
        }
    }
}

2023-06-28 23:32:25 [t1] c.dataContainerStamped - optimistic read locking… 256
2023-06-28 23:32:26 [t2] c.dataContainerStamped - write lock 384
2023-06-28 23:32:26 [t1] c.dataContainerStamped - updating to read lock… 256
2023-06-28 23:32:28 [t2] c.dataContainerStamped - write unlock 384
2023-06-28 23:32:28 [t1] c.dataContainerStamped - read lock 513
2023-06-28 23:32:29 [t1] c.dataContainerStamped - read finish… 513
2023-06-28 23:32:29 [t1] c.dataContainerStamped - read unlock 513

你可能感兴趣的:(并发编程,java,开发语言)