How It Works: SQL Server Lock Iteration / Enumeration


Moved from: bobsql.com

 

When executing a query to enumerate the locks, such as select * from sys.dm_tran_locks, how does SQL Server scan the locks and avoid impacting the overall concurrency?

I recently posted on aspects of the SQL Server Lock Manager and found the iteration of the locks interesting as I was stepping in the code.

https://bobsql.com/how-it-works-sql-server-login_stats-sys-dm_exec_sessions https://bobsql.com/how-it-works-sql-server-lock-partitioning

SQL Server has a lock iterator class which is used by Lock Monitor (deadlock detection), DMVs such as dm_tran_locks and other workers.   The iterator is designed to remain lock free whenever possible to avoid contention with active queries.  To accomplish