Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server APP LOCK Mode: Syntax and Usage

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You cannot call applock_mode as a standalone function in SQL Server. It is not a built-in system function. Instead, application locks are managed through the stored procedures sp_getapplock and sp_releaseapplock, and the lock mode is passed as a parameter to sp_getapplock. The mode values are Shared, Update, Exclusive, IntentShared, IntentExclusive, and Shared (with variations). This guide explains how to use these procedures correctly, what each lock mode means, and how to avoid common pitfalls.

What You'll Need

  • SQL Server 2005 or later (application locks are available in all editions).
  • Permission to execute sp_getapplock and sp_releaseapplock in the database (members of public can execute by default, but the procedure checks permissions on the resource).
  • A database connection (the lock is scoped to the database and the principal).
  • Basic familiarity with T-SQL and transactions.

Step-by-Step

  1. Understand the lock modes. sp_getapplock accepts a @LockMode parameter with these values:
    • Shared – multiple sessions can hold the same shared lock simultaneously; blocks exclusive locks.
    • Update – a middle ground that prevents deadlocks when multiple sessions intend to update; only one session can hold an update lock at a time, but shared locks can coexist.
    • Exclusive – only one session can hold the lock; blocks all other lock modes.
    • IntentShared – indicates intent to acquire a shared lock at a finer granularity; used internally, rarely needed directly.
    • IntentExclusive – indicates intent to acquire an exclusive lock at a finer granularity.
    The default is Shared if not specified.
  2. Open a transaction. Application locks are held until the transaction commits or rolls back, or until explicitly released. Always wrap sp_getapplock in a transaction to ensure proper release. For example:
    BEGIN TRANSACTION;
    DECLARE @result int;
    EXEC @result = sp_getapplock
        @Resource = 'MyAppLock',
        @LockMode = 'Exclusive',
        @LockOwner = 'Transaction',
        @LockTimeout = 5000;
    IF @result < 0
    BEGIN
        ROLLBACK TRANSACTION;
        -- Handle lock acquisition failure
    END
    ELSE
    BEGIN
        -- Critical section
        COMMIT TRANSACTION;
    END
  3. Choose the lock owner. The @LockOwner parameter can be Transaction (default) or Session. Use Transaction when you want the lock released automatically at the end of the transaction. Use Session when you need the lock to persist beyond a transaction (e.g., across multiple batches); then you must explicitly release it with sp_releaseapplock.
  4. Set a lock timeout. The @LockTimeout parameter (in milliseconds) controls how long sp_getapplock waits for the lock. The default is the session's LOCK_TIMEOUT setting. A value of 0 means immediate failure if the lock is not available; -1 means wait indefinitely. Always handle the return code: 0 or positive indicates success, negative indicates failure (e.g., -1 timeout, -2 cancelled, -3 deadlock, -999 parameter error).
  5. Release the lock. If you used @LockOwner = 'Session', call sp_releaseapplock with the same resource name and owner. For transaction-owned locks, the lock is released automatically on commit or rollback. Example:
    EXEC sp_releaseapplock @Resource = 'MyAppLock', @LockOwner = 'Session';
  6. Use a consistent resource name. The resource name is a string (up to 255 characters) that identifies the lock. Use a naming convention that includes the application name and purpose, e.g., 'MyApp:OrderProcessing'. The lock is scoped to the current database and the principal (user) that owns it, so different users can acquire locks with the same name without conflict.
  7. Test concurrency. Open two query windows. In the first, begin a transaction and acquire an exclusive lock. In the second, attempt to acquire the same lock with a short timeout; it should fail with a negative return code. This verifies the lock is working.

Common Mistakes

  • Forgetting to handle the return code. sp_getapplock returns a status code, not an error. If you ignore it, your code may proceed without holding the lock, leading to race conditions.
  • Using Session owner without releasing. Session-owned locks persist until the session ends or you explicitly release them. If you forget, other sessions may block indefinitely.
  • Assuming the lock is global. Application locks are scoped to the current database and the principal. Two different users can hold the same lock name simultaneously if they are different principals. To create a global lock, use a consistent principal (e.g., a dedicated user) or use a different mechanism.
  • Mixing lock modes incorrectly. Using Update mode where Exclusive is needed can allow concurrent access that violates your logic. Understand the compatibility matrix: Shared is compatible with Shared and Update; Update is compatible with Shared but not Update or Exclusive; Exclusive is incompatible with all.
  • Not using transactions. If you use @LockOwner = 'Transaction' but forget to begin a transaction, the lock is acquired and released immediately (auto-commit), providing no protection.

Tips

  • Use sp_getapplock to serialize access to external resources (e.g., a file, a web service) or to implement custom concurrency control beyond what row-level locking provides.
  • Keep the lock duration as short as possible to minimize blocking. Acquire the lock, perform the critical work, then commit or release.
  • Choose @LockTimeout based on your application's tolerance for waiting. A short timeout with retry logic is often better than a long block.
  • Monitor application locks using sys.dm_tran_locks where resource_type = 'APPLICATION'.
  • Document your lock names and modes to avoid conflicts between different parts of the application.

Troubleshooting

  • Lock not acquired (return code -1). The timeout expired. Check if another session holds a conflicting lock. Increase @LockTimeout or investigate the blocking session using sp_who2 or sys.dm_exec_requests.
  • Deadlock (return code -3). Two sessions are waiting for locks in a circular pattern. Use SET DEADLOCK_PRIORITY or redesign to acquire locks in a consistent order.
  • Lock not released. If using Session owner, ensure sp_releaseapplock is called. If using Transaction owner, ensure the transaction is committed or rolled back. Check for open transactions in the session.
  • Permission denied. The procedure checks permissions on the resource. Ensure the user has the necessary rights; by default, public can execute, but the resource name may be restricted. Grant EXECUTE on sp_getapplock if needed.
  • Unexpected blocking. Use sys.dm_tran_locks to identify application locks and the sessions holding them. Query resource_description to see the lock name.

Frequently Asked Questions

Is applock_mode a real SQL Server function?

No. There is no built-in function named applock_mode. Application locks are managed via sp_getapplock and sp_releaseapplock, and the lock mode is specified as a parameter to sp_getapplock.

What is the difference between Shared and Update lock modes?

Shared allows multiple sessions to hold the lock concurrently, while Update allows only one session to hold it but is compatible with Shared. Update is useful to prevent deadlocks when multiple sessions intend to update a resource.

Can I use application locks across databases?

No. Application locks are scoped to the current database and the principal. To coordinate across databases, you would need to use a common database or a different mechanism.

How do I see which application locks are currently held?

Query sys.dm_tran_locks where resource_type = 'APPLICATION'. The resource_description column shows the lock name.

What happens if I don't release a session-owned lock?

The lock remains held until the session ends (connection closes) or you explicitly call sp_releaseapplock. Other sessions requesting a conflicting lock will block or time out.

Can I use application locks in a stored procedure?

Yes. You can call sp_getapplock inside a stored procedure, but ensure the transaction context is managed correctly. If the procedure is called within an existing transaction, the lock will be released when that transaction ends.