JD.LOCK

JD.LOCK occurs when a lock was acquired with a java.util.concurrent.locks.Lock.lock() method call, but it was never actually released; that is, the java.util.concurrent.locks.Lock.unlock() method was not called on some path.

Vulnerability and risk

This situation can cause deadlock.

Mitigation and prevention

Here is a pattern for implementing locking by means of a Lock object:

l.lock();

try { 
   ...
 } finally {
   l.unlock(); 
}

Example 1

Copy
     void action() {
         Lock l = new ReentrantLock();
         l.lock();
         try {
             dosomething();
         } catch (Exception e) {
             l.unlock();
         }
     }
 
     private void dosomething() throws Exception {
         // ...
     }

JD.LOCK is reported for the line 13: Lock 'l' acquired but not released.

Example 2

Copy
     void action() {
         Lock l = new ReentrantLock();
         l.lock();
         try {
             dosomething();
         } catch (Exception e) {
             // ...
         } finally {
             l.unlock();
         }
     }
 
     private void dosomething() throws Exception {
         // ...
     }

The problem from the previous snippet is fixed: the lock would be released whether an exception was thrown or not. JD.LOCK is not reported here.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning Java analysis for more information.