亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案

 更新時(shí)間:2022年06月06日 12:28:42   作者:Gevin  
在筆者面試過程時(shí),經(jīng)常會(huì)被問到各種各樣的鎖,如樂觀鎖、讀寫鎖等等,非常繁多,下面這篇文章主要給大家介紹了關(guān)于Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

Python 提供了 try-with-lock,不需要顯式地獲取和釋放鎖,非常方便。Java 沒有這樣的機(jī)制,不過我們可以自己實(shí)現(xiàn)這個(gè)機(jī)制。

本文以訪問量統(tǒng)計(jì)的簡(jiǎn)化場(chǎng)景為例,介紹相關(guān)內(nèi)容,即:

public class VisitCounter {
    @Getter
    private long visits = 0;

    public void visit() {
        visits++;
    }
}

這里的visit()方法,是線程不安全的,若多線程并發(fā)訪問該方法,visits結(jié)果是錯(cuò)的。因此多線程下需要上鎖,即:

public void safeVisit() {
    try {
        lock.lock();
        visits++;
    } finally {
        lock.unlock();
    }
}

為避免lock... unlock的麻煩,本文提供了以下幾種封裝思路,僅供參考。

方案1 使用AutoCloseable

java7 開始提供的AutoCloseable接口,實(shí)現(xiàn)了try-with-resources功能,可以利用它來實(shí)現(xiàn)鎖的自動(dòng)釋放。

public class AutoCloseableLock implements AutoCloseable{
    private final Lock lock;

    public AutoCloseableLock(Lock lock) {
        this.lock = lock;
    }

    @Override
    public void close() throws Exception {
        lock.unlock();
    }

    public void lock() {
        lock.lock();
    }

    public boolean tryLock() {
        return lock.tryLock();
    }

    public void lockInterruptibly() throws InterruptedException {
        lock.lockInterruptibly();
    }
}

應(yīng)用:

public void safeVisit() throws Exception {
    try (AutoCloseableLock autoCloseableLock = new AutoCloseableLock(lock)) {
        autoCloseableLock.lock();
        visits++;
    } 
}

方案2 使用lambda

得益于lambda和函數(shù)式編程的使用,Java 8 開始鼓勵(lì)“行為參數(shù)化”,實(shí)現(xiàn)了環(huán)繞執(zhí)行模式。說白了,類似于代理模式,把要上鎖執(zhí)行的代碼,放到一個(gè)lambda表達(dá)式中,在lambda之外套上try lock ... finally的外殼,由于lambda作為上鎖代碼的載體,是以參數(shù)形式傳入的,因此具備通用性。這段文字描述的,即下面代碼中的runWithLock(Runable)方法,這就是所謂的“環(huán)繞執(zhí)行模式”。雖然文字描述不好理解,看代碼一目了然。

public class AutoReleaseLockHolder {
    private final Lock lock;

    public AutoReleaseLockHolder(Lock lock) {
        this.lock = lock;
    }

    public void runWithLock(Runnable runnable) {
        try {
            lock.lock();
            runnable.run();
        } finally {
            lock.unlock();
        }
    }

    public boolean runWithTryLock(Runnable runnable) {
        try {
            boolean locked = lock.tryLock();
            if (!locked) {
                return false;
            }
            runnable.run();
            return true;
        } finally {
            lock.unlock();
        }
    }


    public void runWithLockInterruptibly(Runnable runnable) 
                throws InterruptedException {
        try {
            lock.lockInterruptibly();
            runnable.run();
        } finally {
            lock.unlock();
        }
    }
}

使用:

public void safeVisit() {
    lockHolder.runWithLock(() -> visits++);
}

方案3 代理模式

通過代理模式,也可以把上鎖解鎖的操作獨(dú)立出來,變得通用,這種方式的主要問題在于,會(huì)對(duì)整個(gè)函數(shù)上鎖,鎖的顆粒度較大,降低系統(tǒng)的并行度,從而影響系統(tǒng)性能。 但作為思路拓展練練手。

如果對(duì)接口定義的方法做代理,可以使用java的動(dòng)態(tài)代理,如果想對(duì)整個(gè)類的方法都做代理,可以使用Cglib。

(1)動(dòng)態(tài)代理

創(chuàng)建代理對(duì)象:

public Object createAutoLockProxy(Object target) {
        Class<?>[] interfaces = target.getClass().getInterfaces();
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), interfaces, (proxy, method, args) -> {
            try {
                lock.lock();
                return method.invoke(target, args);
            } finally {
                lock.unlock();
            }
        });
    }

使用:

public void safeVisitCountWithDynamicProxy() throws InterruptedException {
        long total = 20000;
        int current = 10;
        IVisitCounter visit = (IVisitCounter )new DynamicLockProxy(new ReentrantLock()).createAutoLockProxy2(visitCounter);
        concurrentVisit(total, current, visit::visit);
        System.out.println("actual visits: " + visit.getVisits());
    }

(2)Cglib

創(chuàng)建代理對(duì)象:

public static <T> T createAutoLockObject(Class<T> objectClass, Lock lock) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(objectClass);
    enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
        try {
            lock.lock();
            return proxy.invokeSuper(obj, args);
        } finally {
            lock.unlock();
        }
    });
    return (T) enhancer.create();
}

使用:

public void safeVisitCountWithCglib() throws InterruptedException {
    long total = 20000;
    int current = 10;
    Lock lock = new ReentrantLock();
    VisitCounter visitCounterProxy = CglibLockProxy.createAutoLockObject(VisitCounter.class, lock);
    concurrentVisit(total, current, visitCounterProxy::visit);
    System.out.println("actual visits: " + visitCounterProxy.getVisits());
}

Show me the code

以上幾個(gè)方案的代碼,我已放到GitHub上的try-with-lock-example 倉庫中,大家可以去看一下源碼。

動(dòng)態(tài)代理的兩個(gè)方案,調(diào)用方法做了簡(jiǎn)化處理,調(diào)用了其他函數(shù),但因?yàn)榕c主題無關(guān),沒有放入正文,可以在源碼倉庫看看文中沒寫的代碼。

另外,代碼倉庫中,也包含了測(cè)試,我默認(rèn)用10個(gè)線程,對(duì)VisitCounter并發(fā)調(diào)用了20000次,在單線程、線程不安全訪問和各種方案的加鎖訪問,結(jié)果如下:

total: 20000 visits: 20000
total: 20000 visits: 6739
total: 20000 visits: 20000
total: 20000 visits: 20000
total: 20000 visits: 20000
total: 20000 visits: 20000

總結(jié)

到此這篇關(guān)于Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案的文章就介紹到這了,更多相關(guān)Java自動(dòng)釋放鎖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 關(guān)于Maven依賴沖突解決之exclusions

    關(guān)于Maven依賴沖突解決之exclusions

    這篇文章主要介紹了關(guān)于Maven依賴沖突解決之exclusions用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot集成swagger-ui以及swagger分組顯示操作

    SpringBoot集成swagger-ui以及swagger分組顯示操作

    這篇文章主要介紹了SpringBoot集成swagger-ui以及swagger分組顯示操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • java基礎(chǔ)(System.err和System.out)詳解

    java基礎(chǔ)(System.err和System.out)詳解

    下面小編就為大家?guī)硪黄猨ava基礎(chǔ)(System.err和System.out)詳解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • Spring Cloud Consul的服務(wù)注冊(cè)與發(fā)現(xiàn)

    Spring Cloud Consul的服務(wù)注冊(cè)與發(fā)現(xiàn)

    這篇文章主要介紹了Spring Cloud Consul服務(wù)注冊(cè)與發(fā)現(xiàn)的實(shí)現(xiàn)方法,幫助大家更好的理解和學(xué)習(xí)使用spring框架,感興趣的朋友可以了解下
    2021-02-02
  • Json字符串內(nèi)容比較超實(shí)用教程

    Json字符串內(nèi)容比較超實(shí)用教程

    這篇文章主要介紹了Json字符串內(nèi)容比較-超實(shí)用版,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-09-09
  • java中構(gòu)造方法和普通方法的區(qū)別說明

    java中構(gòu)造方法和普通方法的區(qū)別說明

    這篇文章主要介紹了java中構(gòu)造方法和普通方法的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • 詳解Java運(yùn)算中的取余

    詳解Java運(yùn)算中的取余

    這篇文章主要介紹了java運(yùn)算中的取余,在java運(yùn)算中,取余符號(hào)是?%,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-05-05
  • Java實(shí)現(xiàn)讀取html文本內(nèi)容并按照格式導(dǎo)出到excel中

    Java實(shí)現(xiàn)讀取html文本內(nèi)容并按照格式導(dǎo)出到excel中

    這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)讀取html文本提取相應(yīng)內(nèi)容按照格式導(dǎo)出到excel中,文中的示例代碼講解詳細(xì),需要的可以參考下
    2024-02-02
  • SpringMVC訪問靜態(tài)資源的方法

    SpringMVC訪問靜態(tài)資源的方法

    本篇文章主要介紹了SpringMVC訪問靜態(tài)資源的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-02-02
  • 線上Spring CPU 高負(fù)載解決思路詳解

    線上Spring CPU 高負(fù)載解決思路詳解

    這篇文章主要為大家介紹了線上Spring CPU 高負(fù)載解決思路詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09

最新評(píng)論