ITeye博客

Lock的实现原理

daniel0202 · 2014-01-15 17:27 · 并发 · 编程语言 · Markdown

两种加锁方式:

Synchronized(obj){do logic}:尝试获取obj的锁,如果无法获取则阻塞等待;

Lock:它的实现原理和Synchronized完全不同,它使用compare and swap理念,如果符合cas判定逻辑,那么就修改state状态,把当前线程设定为独占,具体代码为:


        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

无法获取锁的话,那么就:


    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

但是为啥tryAcquire直接抛出异常说UnsupportedOperationException呢,不明白


    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }

Lock很重要的一个方面是它可以tryLock,试图获取不成的话可以不用阻塞,Synchronized的话那就等吧,等着cpu调度到你这个线程,你就可以做事了。

AtomicInteger实现原子性的原理如下:


    /**
     * Atomically increments by one the current value.
     *
     * @return the updated value
     */
    public final int incrementAndGet() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return next;
        }
    }

一、get()获取的是本地private volatile int value,这样保证可见性; 二、如果内存中的值是current,则设置为next 三、如果if (compareAndSet(current, next))返回false,看到for (;;)了吗?其他线程修改完了不就等到我了吗,O(∩_∩)O哈哈~

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。