简体   繁体   中英

Why is there no synchronized keyword used in Java lock implementations?

synchronized is used in Java to deal with mutex sort of things. However the implementations of Lock interface like ReentrantLock in Java does not use this keyword. All the code looks just normal code. Then how does it handle multiple threads on earth?

I believe the following code pieces are related:

The tryAcquire method in Sync of the ReentrantLock

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (!hasQueuedPredecessors() &&
            compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    return false;
}

Sync extends AbstractQueuedSynchronizer and the code related:

final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

So seems no synchronized keyword is used then how does it guarantee mutex?

Since Java 1.5(?) there is JVM support for hardware locking using so called Compare-And-Swap methods. Just follow the sources until the point when this is called.

Also see Doug Lea's paper for better understanding: http://gee.cs.oswego.edu/dl/papers/aqs.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM