Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top