11-1. Java中的重入鎖、讀寫鎖、自定義鎖實(shí)現(xiàn)

前言:上一節(jié)講述了鎖的原理,這節(jié)先講解鎖的應(yīng)用,再通過上節(jié)的原理來(lái)實(shí)現(xiàn)一個(gè)自定義的鎖。

1 從鎖開始講起

1.1 lock

在java.util.concurrent.locks.Lock.java中的源碼解釋:

根據(jù)Lock接口的源碼注釋,Lock接口的實(shí)現(xiàn),具備和同步關(guān)鍵字同樣的內(nèi)存語(yǔ)義。

lock的常用API
lock.lock(); // 如果一個(gè)線程拿到鎖,其他線程會(huì)等待
lock.tryLock(); // 嘗試獲取鎖,獲取不到立即返回
lock.tryLock(1000L); // 嘗試獲取鎖1秒,獲取不到也立即返回

1.1.1 可重入鎖ReentrantLock

package szu.vander.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Vander
 * @date :   2019/12/7
 * @description : 可重入鎖
 */
public class ReentrantDemo {

    private final static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args){
        reentrantLock.lock();
        try {
            System.out.println("第1次獲取鎖");
            System.out.println("this thread lock hold count : " + reentrantLock.getHoldCount());
            reentrantLock.lock();
            System.out.println("第2次獲取鎖");
            System.out.println("this thread lock hold count : " + reentrantLock.getHoldCount());
        } finally {
            reentrantLock.unlock();
            reentrantLock.unlock();
        }
        System.out.println("this thread lock hold count : " + reentrantLock.getHoldCount());

        new Thread(() -> {
            System.out.println(Thread.currentThread() + ": expect to get the lock!");
            reentrantLock.lock();
            System.out.println(Thread.currentThread() + ": had get the lock!");
        }).start();

    }

}

運(yùn)行結(jié)果

這里說明一下ReentrantLock有公平和非公平之分。(公平鎖就是哪個(gè)線程等得久就讓哪個(gè)線程先執(zhí)行)

1.1.2 可響應(yīng)中斷的ReentrantLock

package concurrent.lock;

import java.time.Instant;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Vander
 * @date :   2019/12/8
 * @description : 獲取鎖后可被中斷
 */
public class LockInterruptiblyDemo {

    private Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        LockInterruptiblyDemo lockInterruptiblyDemo = new LockInterruptiblyDemo();
        Runnable runnable = () -> {
            try {
                lockInterruptiblyDemo.getLockAndInterrupt();
            } catch (InterruptedException e) {
                Instant now = Instant.now();
                System.out.println(String.format("%s - %s : in the main runnable func, being interrupt, %s"
                        , now
                        , Thread.currentThread()
                        , e.toString()));
            }
        };
        Thread thread0 = new Thread(runnable);
        Thread thread1 = new Thread(runnable);

        try {
            thread0.start();
            Thread.sleep(500); // 等待0.5秒,讓thread0先執(zhí)行

            thread1.start();
            Thread.sleep(2000); // 兩秒后,中斷thread1

            thread1.interrupt(); // 處于Sleep狀態(tài)或處于lockInterruptibly狀態(tài)能被中斷
        } catch (InterruptedException e) {
            Instant now = Instant.now();
            System.out.println(String.format("%s - %s : in the main func, being interrupt, %s"
                    , now
                    , Thread.currentThread()
                    , e.toString()));
        }

    }

    public void getLockAndInterrupt() throws InterruptedException {
        Instant now = Instant.now();
        System.out.println(String.format("%s - %s : expect the this lock", now, Thread.currentThread()));
        lock.lockInterruptibly();// 阻塞,能立即響應(yīng)中斷,lock.lock(),阻塞且不立即響應(yīng)中斷
        try {
            now = Instant.now();
            System.out.println(String.format("%s - %s : get the this lock" +
                    ", and start sleep 10s", now, Thread.currentThread()));
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            now = Instant.now();
            System.out.println(String.format("%s - %s : in the getLockAndInterrupt func, being interrupt, %s"
                    , now
                    , Thread.currentThread()
                    , e.toString()));
        } finally {
            now = Instant.now();
            System.out.println(String.format("%s - %s : run into finally", now, Thread.currentThread()));
            lock.unlock();
            System.out.println(String.format("%s - %s : release the this lock", now, Thread.currentThread()));
        }

    }

}

運(yùn)行結(jié)果:線程0獲得了鎖,并處于Sleep狀態(tài),線程1進(jìn)入阻塞并且能響應(yīng)中斷的狀態(tài),將線程1中斷,線程1可以響應(yīng)中斷。

2)改為lock.lock()

運(yùn)行結(jié)果:改成lock()之后,線程1就不立即響應(yīng)中斷了,它會(huì)一直等鎖,然后進(jìn)入Sleep的時(shí)候才發(fā)現(xiàn)中斷狀態(tài)為已經(jīng)被改變了,才去響應(yīng)中斷

1.1.3 讀寫鎖(ReadWriteLock)

為了提高讀操作比寫操作多的場(chǎng)景的性能,設(shè)計(jì)出了讀寫鎖的思路。當(dāng)某個(gè)線程進(jìn)行寫操作時(shí),所以進(jìn)行讀操作的線程都不能來(lái)讀,因?yàn)檫@樣有可能會(huì)讀取到臟數(shù)據(jù);另一種情況是,如果某個(gè)線程僅僅是來(lái)讀數(shù)據(jù)的,總不能讓其它讀數(shù)據(jù)的線程不能來(lái)讀吧,所以這種情況下的讀鎖是可以共享的,屬于共享鎖。而第一種情況的寫數(shù)據(jù)時(shí),鎖是互斥的,屬于互斥鎖,也稱為獨(dú)享鎖。

設(shè)計(jì)思路:維護(hù)一對(duì)關(guān)聯(lián)鎖,一個(gè)用于只讀操作,一個(gè)用于寫入操作;
讀鎖可以由多個(gè)讀線程同時(shí)持有,而寫鎖是排他的,互斥的。

示例場(chǎng)景
緩存組件、集合的并發(fā)線程安全性改造。

鎖降級(jí)(解決讀取兩次數(shù)據(jù)的數(shù)據(jù)不一致問題)
寫鎖是線程獨(dú)占,讀鎖是共享,所以寫->讀是降級(jí)。(讀->寫,是不能實(shí)現(xiàn)的,因?yàn)槌钟凶x鎖的情況下,是不能再持有寫鎖的)
在讀寫鎖中還會(huì)提到的概念是鎖降級(jí)指的是寫鎖降級(jí)成為讀鎖。持有當(dāng)前擁有的寫鎖的同時(shí),再獲取到讀鎖,隨后釋放寫鎖的過程。

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author : Vander
 * @date :   2019/12/8
 * @description : 這里既是讀寫鎖的一種常見應(yīng)用,也是鎖降級(jí)的常用之處
 */
public class CacheDataDemo<T> {

    /**
     * hashMap不是線程安全的
     */
    private Map<String, T> cache = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public T get(String key) {
        // 獲取讀鎖,保證讀期間,數(shù)據(jù)沒有被修改
        readWriteLock.readLock().lock();
        if(cache.get(key) == null) {
            // 從數(shù)據(jù)庫(kù)中讀取,并寫入緩存
            try {
                T value = getDataFromDB(key);
                // 先釋放讀鎖
                readWriteLock.readLock().unlock();
                // 獲取寫鎖
                readWriteLock.writeLock().lock();
                // 再次判斷是否對(duì)應(yīng)的Key的緩存為空,這是為了防止獲取寫鎖的過程中,已經(jīng)有其它線程寫入了緩存
                // 往緩存中寫數(shù)據(jù)
                if(cache.get(key) == null) {
                    cache.put(key, value);
                }
                // 鎖降級(jí):持有寫鎖過程中,再獲取讀鎖,再釋放寫鎖:寫鎖->讀鎖
                readWriteLock.readLock().lock();
            } finally {
                // 進(jìn)行后續(xù)操作,可能需要繼續(xù)進(jìn)行讀取數(shù)據(jù)的操作
                readWriteLock.writeLock().unlock();
            }

        }
        T value = cache.get(key);
        readWriteLock.readLock().unlock();
        return value;
    }

    private T getDataFromDB(String key) {
        // 模擬從數(shù)據(jù)庫(kù)中讀取數(shù)據(jù)
        return (T)new Object();
    }

}

2.1 實(shí)現(xiàn)一個(gè)自定義的鎖

2.1.1 從原理開始講解

上一節(jié)講解了synchronized同步關(guān)鍵字,從偏向鎖->輕量級(jí)鎖->重量級(jí)鎖,自己實(shí)現(xiàn)的Lock,先不實(shí)現(xiàn)這么復(fù)雜的東西,從簡(jiǎn)單的思路出發(fā),我們直接來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的重量級(jí)鎖,重量級(jí)鎖中有兩個(gè)重要的屬性:鎖池(等待池,即多個(gè)線程爭(zhēng)搶這個(gè)鎖,記錄下這些線程爭(zhēng)搶這個(gè)鎖的Pool)、鎖的擁有者,這里我們先實(shí)現(xiàn)一個(gè)不可重入的鎖,就先不記錄鎖的狀態(tài)了。

基本思路:


package szu.vander.lock;

import szu.vander.log.LogLevel;
import szu.vander.log.Logger;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * @author : Vander
 * @date :   2019/12/8
 * @description : 自定義Lock實(shí)現(xiàn)
 */
public class UserDefinedLock implements Lock {

    private final static Logger log = new Logger(false, LogLevel.INFO.getLevel());

    /**
     * 存放爭(zhēng)搶鎖的線程信息
     */
    private volatile LinkedBlockingQueue<Thread> waitLockPool = new LinkedBlockingQueue<>();
    /**
     * 當(dāng)前鎖的擁有者,存放線程信息
     */
    private volatile AtomicReference<Thread> owner = new AtomicReference<>();

    @Override
    public boolean tryLock() {
        if (owner.get() == null) {
            return setOwner(Thread.currentThread());
        }
        return false;
    }

    @Override
    public void lock() {
        // 鎖池中的每個(gè)線程都要來(lái)嘗試爭(zhēng)搶鎖
        while (!tryLock()) {
            // 將等待鎖的線程放入等待池中
            waitLockPool.add(Thread.currentThread());
            // 對(duì)于沒有搶到鎖的線程全都阻塞
            log.info("begin to park");
            LockSupport.park(Thread.currentThread());
        }
        waitLockPool.remove(Thread.currentThread());
    }

    @Override
    public void unlock() {
        // 當(dāng)前線程執(zhí)行了解鎖
        if (owner.compareAndSet(Thread.currentThread(), null)) {
            // 通知等待池中的所有線程去爭(zhēng)搶鎖
            for (Thread thread: waitLockPool) {
                // 此處如果使用waitLockPool.poll去遍歷,速度將會(huì)非常慢
                LockSupport.unpark(thread);
            }
        }
    }

    /**
     * 使用CAS機(jī)制來(lái)修改owner的值
     *
     * @param owner
     */
    private boolean setOwner(Thread owner) {
        return this.owner.compareAndSet(null, owner);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }

    public static void main(String[] args) {
        Lock lock = new UserDefinedLock();
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                lock.lock();
                log.info("get the this lock, and start sleep");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("release the this lock");
                lock.unlock();
            }
        };
        for (int i = 0; i < 5; i++) {
            new Thread(runnable1).start();
        }

    }

}

測(cè)試代碼:

package szu.vander.test.lock;

import szu.vander.lock.UserDefinedLock;

import java.util.concurrent.TimeUnit;

/**
 * @author : Vander
 * @date :   2019/12/8
 * @description :
 */
public class UserDefinedLockTest {

    private static int sum = 0;

    private static UserDefinedLock lock = new UserDefinedLock();

    private static int add() {
        lock.lock();
        sum++;
        lock.unlock();
        return sum;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    add();
                }
            }
        };
        for (int i = 0; i < 10; i++) {
            new Thread(runnable).start();
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println("Result : " + sum);
    }


}

運(yùn)行結(jié)果:使用10個(gè)線程同時(shí)進(jìn)行累加,不會(huì)出現(xiàn)加不滿10w的情況,說明自定義鎖也不會(huì)存在并發(fā)問題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容