How do you check if a Thread holds a lock or not?

Java provides Thread.holdsLock(Object obj), a static method that returns true if the currently executing thread holds the intrinsic (monitor) lock on the given object, which is mainly useful for debugging, assertions, and validating locking assumptions.

Key Points: • Thread.holdsLock() only checks the calling thread's own lock ownership — it can't be used to inspect an arbitrary other thread's locks. • It only covers intrinsic locks (synchronized), not explicit locks like ReentrantLock, which instead expose isHeldByCurrentThread() for the same purpose. • It's commonly used inside assert statements to enforce that a method is only ever called while a particular lock is already held. • For broader lock-state inspection across all threads (e.g. detecting deadlocks), tools like jstack or ThreadMXBean.findDeadlockedThreads() are the appropriate approach instead. • It doesn't block or acquire anything — it's a pure, fast state check.

Example: A private helper method that assumes the caller already holds a lock on the accounts object can start with assert Thread.holdsLock(accounts) : "must hold accounts lock", catching a programming mistake early during development and testing.

Code Example:

private void updateBalanceInternal(Account acc, BigDecimal amount) {
    assert Thread.holdsLock(acc) : "caller must hold lock on account";
    acc.setBalance(acc.getBalance().add(amount));
}

Interview Tip: A concise interview answer is:

"For intrinsic locks, Thread.holdsLock(obj) tells the current thread whether it holds the monitor on that object, which is handy in assertions to validate locking assumptions during development. For ReentrantLock, the equivalent is lock.isHeldByCurrentThread(). Neither lets you inspect another thread's locks directly — for that you'd reach for a thread dump or ThreadMXBean."