Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

An exceptional condition can circumvent the release of a lock, leading to deadlock. According to the Java API [API 20062014]:

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread.

Consequently, an unreleased lock in any thread will prevent other threads from acquiring the same lock. Programs must release all actively held locks on exceptional conditions. Intrinsic locks of class objects used for method and block synchronization are automatically released on exceptional conditions (such as abnormal thread termination).

This guideline is an instance of FIO04-J. Release resources when they are no longer needed.  HoweverHowever, most Java lock objects are not Closeablecloseable, so they cannot be automatically released using Java 7's try-with-resources feature.

Noncompliant Code Example (Checked Exception)

This noncompliant code example protects a resource, an open file, by using a ReentrantLock. However, the method fails to release the lock when an exception occurs while performing operations on the open file. When an exception is thrown, control transfers to the catch block and the call to unlock() never executes.

Code Block
bgColor#FFcccc
public final class Client {
  public void doSomething(File file) {
    private final Lock lock = new ReentrantLock();

  public void doSomething(File file) {
    InputStream in = null;
    try {
      in = new lock.lockFileInputStream(file);
      in = new FileInputStream(filelock.lock();

      // Perform operations on the open file

      lock.unlock();
    } catch (FileNotFoundException x) {
      // Handle exception
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException x) {
          // Handle exception
        }  
      }
    }
  }
}

...

This noncompliant code example attempts to rectify the problem of the lock not being released , by invoking Lock.unlock() in the finally block. This code ensures that the lock is released regardless of whether or not an exception occurs. However, it does not acquire the lock until after trying to open the file. If the file cannot be opened, the lock may be unlocked without ever being locked in the first place.

Code Block
bgColor#FFcccc
public final class Client {
  public void doSomething(File file) {
   private final Lock lock = new ReentrantLock();

  public void doSomething(File file) {
    InputStream in = null;
    try {
      in = new FileInputStream(file);
      lock.lock();
      // Perform operations on the open file
    } catch (FileNotFoundException fnf) {
      // Forward to handler
    } finally {
      lock.unlock();
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // Forward to handler
        }
      }
    }
  }
}

...

Code Block
bgColor#ccccff
public final class Client {
  public void doSomething(File file) {
    private final Lock lock = new ReentrantLock();

  public void doSomething(File file) {
    InputStream in = null;
    lock.lock();
    try {
      in = new FileInputStream(file);
      // Perform operations on the open file
    } catch (FileNotFoundException fnf) {
      // Forward to handler
    } finally {
      lock.unlock();

      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // Forward to handler
        }
      }
    }
  }
}

...

Code Block
bgColor#ccccff
public interface LockAction {
  void doSomethingWithFile(InputStream in);
}

public final class ReentrantLockAction {
  private static final Lock lock = new ReentrantLock();

  public static void doSomething(File file, LockAction action)  {
    Lock lock = new ReentrantLock();
    InputStream in = null;
    lock.lock();
    try {
      in = new FileInputStream(file);
      action.doSomethingWithFile(in);
    } catch (FileNotFoundException fnf) {
      // Forward to handler
    } finally {
      lock.unlock();

      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // Forward to handler
        }
      }
    }
  }
}

public final class Client {
  public void doSomething(File file) {
    ReentrantLockAction.doSomething(file, new LockAction() {
      public void doSomethingWithFile(InputStream in) {
        // Perform operations on the open file
      }
    });
  }
}

...

This noncompliant code example uses a ReentrantLock to protect a java.util.Date instance – recall instance—recall that java.util.Date is thread-unsafe by design.

Code Block
bgColor#FFcccc
final class DateHandler {

  private final Date date = new Date();

  private final Lock lock = new ReentrantLock();

  // str could be null
  public void doSomething(String str) {
    lock.lock();
    String dateString = date.toString();
    if (str.equals(dateString)) {
      // ...
    }
    // ...

    lock.unlock();
  }
}

...

Code Block
bgColor#ccccff
final class DateHandler {

  private final Date date = new Date();

  private final Lock lock = new ReentrantLock();

  // str could be null
  public void doSomething(String str) {
    lock.lock();
    try {
      String dateString = date.toString();
      if (str != null && str.equals(dateString)) {
        // ...
      }
      // ...

    } finally {
      lock.unlock();
    }
  }
}

...

Failure to release locks on exceptional conditions could lead to thread starvation and deadlock.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

LCK08-J

low

Low

likely

Likely

low

Low

P9

L2

Automated Detection

Some static analysis tools are capable of detecting violations of this rule.

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.LCK08.RLF
CERT.LCK08.LOCK
Release Locks in a "finally" block
Do not abandon unreleased locks
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V

CCE_LK_UNRELEASED_ON_EXN

Implemented

Related Vulnerabilities

The GERONIMO-2234 issue report describes a vulnerability in the Geronimo application server. If the user single-clicks the keystore portlet, the user will lock the default keystore without warning. This causes a crash and stack trace to be produced. FuthermoreFurthermore, the server cannot be restarted because the lock is never cleared.

Related Guidelines

MITRE CWE

CWE-883

.

, Deadlock

Bibliography

 


...

Image Removed Image Removed Image RemovedImage Added Image Added Image Added