java線程--提升"鎖"的效率

1.減小鎖的持有時間

案例jdk 中Pattern類代碼片斷

雙重檢查,減小鎖的持有時間
/**
     * Creates a matcher that will match the given input against this pattern.
     *
     * @param  input
     *         The character sequence to be matched
     *
     * @return  A new matcher for this pattern
     */
    public Matcher matcher(CharSequence input) {
        if (!compiled) {
            synchronized(this) {
                if (!compiled)
                    compile();
            }
        }
        Matcher m = new Matcher(this, input);
        return m;
    }

2.減少鎖粒度

3.讀寫分離

4.鎖分離

案例jdk 中LinkedBlockingQueue類代碼片斷

/** Lock held by take, poll, etc */
    private final ReentrantLock takeLock = new ReentrantLock();

    /** Wait queue for waiting takes */
    private final Condition notEmpty = takeLock.newCondition();

    /** Lock held by put, offer, etc */
    private final ReentrantLock putLock = new ReentrantLock();

    /** Wait queue for waiting puts */
    private final Condition notFull = putLock.newCondition();

5.鎖粗化

相關文章
相關標籤/搜索