StampedLock如何使用?


  • StampedLock 是從 JDK1.8 開始提供,它的性能比 ReadWriteLock 好
  • StampedLock 支持:樂觀讀鎖、悲觀讀鎖、寫鎖
  • StampedLock 的悲觀讀鎖、寫鎖,與 ReadWriteLock 的讀鎖、寫鎖用法相似:讀讀可並行、讀寫互斥、寫寫互斥。
  • StampedLock 之所以性能優於 ReadWriteLock,因為它支持樂觀讀鎖。樂觀讀鎖操作,支持一個線程並發進行寫操作。
  • StampedLock 不支持重入
  • StampedLock 支持鎖的降級和升級
  • StampedLock 可以用悲觀讀鎖調用 readLockInterruptibly() 方法和寫鎖調用 writeLockInterruptibly() 方法,支持可中斷

 

使用示例:

package constxiong.interview;

import java.util.Random;
import java.util.concurrent.locks.StampedLock;

/**
 * 測試 StampedLock
 * @author ConstXiong
 */
public class TestStampedLock {

    private static final StampedLock sl = new StampedLock();
    
    private static volatile int count = 0;
    
    private static final Random r = new Random();
    
    public static void main(String[] args) {
        //啟動 5個線程寫計數,95 個線程讀計數,
        for (int i = 0; i < 100; i++) {
            if (i % 20 == 0) {
                new Thread(() -> {
                    try {
                        Thread.sleep(r.nextInt(10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " 計數新增 1 :" + add());
                }).start();
            } else {
                new Thread(() -> {
                    try {
                        Thread.sleep(r.nextInt(10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " 讀計數:" + read());
                }).start();
            }    
        }
    }
    
    /**
     * 讀取計數
     * @return
     */
    private static int read() {
        int r;
        long stamp = sl.tryOptimisticRead();
        r = count;
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                r = count;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return r; 
    }
    
    /**
     * 計數加 1
     */
    private static int add() {
        long stamp = sl.writeLock();
        try {
            count++;
        } finally {
            sl.unlockWrite(stamp);
        }
        return count;
    }
    
}

 


原文鏈接
 


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM