AbstractQueuedSynchronizer 源码理解

本文详细解析了Java并发编程中的原子操作和同步机制,通过阐述UnSafe类的compareAndSwapInt方法,展示了如何进行不可中断的内存比较与交换。同时,介绍了AbstractQueuedSynchronizer类在并发控制中的应用,通过分析其内部实现,揭示了如何在多线程环境下高效地执行锁操作。文章旨在帮助开发者理解并掌握Java并发编程的核心概念。
UnSafe类(原子操作):
/** 
* 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。 
*  
* @param obj 需要更新的对象 
* @param offset obj中整型field的偏移量 
* @param expect 希望field中存在的值 
* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值 
* @return 如果field的值被更改返回true 
*/  
public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);  
AbstractQueuedSynchronizer类:
     * <p>To enqueue into a CLH lock, you atomically splice it in as new
     * tail. To dequeue, you just set the head field.
     * <pre>
     *      + ------+  prev +----- +       +-----+
     * head |      | <---- |     | <---- |     |  tail
     *      + ------+       +----- +       +-----+
     * </pre>

 /**
     * Inserts node into queue, initializing if necessary. See picture above.
     * @param node the node to insert
     * @return node's predecessor
     */
    private Node enq( final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null ) { // Must initialize
                //如果头部为空,则更新,并赋值给tail
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                //让tail指向新插入的结点
                node. prev = t;
                if (compareAndSetTail(t, node)) {
                    t. next = node;
                    return t;
                }
            }
        }
    }

 /**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared 标明是否共享: addWaiter(Node. EXCLUSIVE) null 
addWaiter(Node. SHARED); new Node();
     * @return the new node
     */
    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node. prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred. next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值