Skip to main content

Lock

Lock

Concept Difference between Lock and Synchronizer AQS

Locks are user-facing, defining the interface for users to interact with locks (e.g., allowing two threads to access in parallel), hiding implementation details;

Synchronizers are for lock implementers, simplifying lock implementation by shielding underlying operations like synchronization state management, thread queuing, waiting, and waking up. Locks and synchronizers isolate the concerns of users and implementers well.

Therefore, the synchronizer provides a CAS-based method to set the tail node: compareAndSetTail(Node expect, Node update). It requires passing the tail node that the current thread "thinks" is correct and the current node. Only after setting successfully does the current node formally establish an association with the previous tail node.

The synchronization queue follows FIFO. The head node is the node that successfully obtained the synchronization state. When the head node's thread releases the synchronization state, it will wake up the successor node. Upon successfully obtaining the synchronization state, the successor node will set itself as the head node, as shown in the figure below.

Setting the head node is done by the thread that successfully obtained the synchronization state. Since only one thread can successfully obtain the synchronization state, the method for setting the head node does not need to use CAS to guarantee execution. It only needs to set the head node to the successor node of the original head node and disconnect the next reference of the original head node.

Reference Materials

  1. Book Name: "The Art of Java Concurrency Programming" Authors: Fang Tengfei, Wei Peng, Cheng Xiaoming
Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
  • Attribution: Retain the original author's signature and code source information in the original and derivative code.
  • Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
The documentation part of this work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License . You may freely share, including copying and distributing this work in any medium or format, and freely adapt, remix, transform, and build upon the material. However, you are required to:
  • Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
  • NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
  • ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.