Synchronized & reentrantLock

Ps: Compare and list the differences.

  1. The keyword needs to be added to the synchronized object, either to a method or to a specific code block, with the object to be locked in parentheses.
  2. Specify start and end positions, lock and unlock, lock&unlock.
  3. Synchronized: If an exception occurs, the synchronized automatically releases the lock, preventing deadlocks.
  4. ReentrantLock: The lock is abnormal and cannot be released. You need to unlock the lock manually.
  5. Sync: reentrant, unfair lock. Lock: Reentrant, can be fair or unfair
  6. Performance: Lock performs better in the case of competitive threads.
    • Sync is implemented by the Jvm and uses the CPU’s pessimistic locking mechanism at the bottom, where threads acquire exclusive locks.
    • Lock is implemented by Java code control using an optimistic locking mechanism, or CAS operation.
    • Sync: A small amount of synchronization
    • Lock: Mass synchronization
  7. Underlying implementation:
    • Sync’s underlying use of instructions to control locks maps to bytecode instructions by adding two commands :monitorEnter, MonitorExit: When the current thread encounters Enter, it attempts to acquire the built-in lock, increments the lock counter if it acquires the lock, and decrement it if exit. The same thread acquires the lock repeatedly when acquiring the same lock, which is reentrant for the lock.
    • The bottom layer of LOCK is CAS optimistic lock, which relies on AQS class to form all request threads into a CLH queue, and all operations on the queue are performed through CAS.

Example:

// sync
private final Object sync = new Object();

public synchronized void sync() {
    System.out.println("You are beautiful,come on!");
}

public void syncS() {
    synchronized (sync) {
        System.out.println("I m get this");
    }
}

// lock
ReentrantLock lock = new ReentrantLock();

public void lock() {
    lock.lock();
    try {
        System.out.println("I love you");
    } finally {
        lock.unlock();
    }
}
Copy the code