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 2014]:

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. However, most Java lock objects are not closeable, 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 {
  private  lock. This can result in thread starvation and deadlock. According to the Java API \[[API 06|AA. Java References#API 06]\], class {{ReentrantLock}} documentation:

{quote}
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.
{quote}

This means that an unreleased lock in any thread will stop other threads from acquiring the same lock. 


h2. Noncompliant Code Example (checked exception)

This noncompliant code example protects a resource by using a {{ReentrantLock}} but fails to release the lock on an exceptional condition. Control flow transfers to the {{catch}} block and the call to {{unlock()}} does not execute.

{code:bgColor=#FFcccc}
public void doSomething(File file) {
  final Lock lock = new ReentrantLock();

  public  tryvoid doSomething(File file) {
    InputStream in = lock.lock();
null;
    try {
     InputStream in = new FileInputStream( filefile);
      lock.lock();

      // DoPerform somethingoperations withon the open file.

      lock.unlock();
    } catch (FileNotFoundException fnfx) {
      // Handle the exception
    }
}
{code}

Note that the lock is not released even when the {{doSomething()}} method returns. 


h2. Compliant Solution

This compliant solution uses a {{try}}-{{finally}} block immediately after acquiring the lock. This ensures that the lock is appropriately released even in the event of an exceptional condition. Also, the lock is acquired outside the try block, which guarantees that the lock is held when the finally block executes.

{code:bgColor=#ccccff}
public void doSomething(File file) {
  finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException x) {
          // Handle exception
        }  
      }
    }
  }
}

Noncompliant Code Example (finally Block)

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 {
  private final Lock lock = new ReentrantLock();

  lock.lock() public void doSomething(File file) {
    InputStream in = null;
    try {
    InputStream  in = new FileInputStream( filefile);
      lock.lock();
      // DoPerform somethingoperations withon the open file.
    } catch (FileNotFoundException fnf) {
      // HandleForward theto exceptionhandler
    } finally {
      lock.unlock();
  }
}
{code}


h2. Noncompliant Code Example (unchecked exception)

This noncompliant code example uses a {{ReentrantLock}} to protect a {{java.util.Date}} instance, which is not thread-safe by design. It also needs to catch {{Throwable}} to be compliant with [EXC06-J. Do not allow exceptions to transmit sensitive information]. 

{mc} Do not declare lock as private as it need package-wide accessibility for illustrative purposes {mc}

{code:bgColor=#FFcccc}
final class     if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // Forward to handler
        }
      }
    }
  }
}

Compliant Solution (finally Block)

This compliant solution encapsulates operations that could throw an exception in a try block immediately after acquiring the lock (which cannot throw). The lock is acquired just before the try block, which guarantees that it is held when the finally block executes.

Code Block
bgColor#ccccff
public final class ClientDateHandler {
  private final DateLock datelock = new DateReentrantLock();

  public void doSomething(File file) {
  final  LockInputStream lockin = new ReentrantLock()null;

  public void doSomethingSafely(String str) {lock.lock();
    try {
      in = doSomethingnew FileInputStream(strfile);
      // Perform operations on the open file
    } catch (ThrowableFileNotFoundException tfnf) {
      // Forward to handler
    }
 finally }

  public void doSomething(String str) {
{
      lock.lockunlock();

    String dateString =if date.toString();
    if (str.equals(dateString)(in != null) {
       // ...
 try {
      }
    lockin.unlockclose();
  }
}
{code}

However, because the {{doSomething()}} method does not} checkcatch (IOException e) {
          // Forward to handler
        }
      }
    }
  }
}

Compliant Solution (Execute-Around Idiom)

The execute-around idiom provides a generic mechanism to perform resource allocation and cleanup operations so that the client can focus on specifying only the required functionality. This idiom reduces clutter in client code and provides a secure mechanism for resource management.

In this compliant solution, the client's doSomething() method provides only the required functionality by implementing the doSomethingWithFile() method of the LockAction interface without having to manage the acquisition and release of locks or the open and close operations of files. The ReentrantLockAction class encapsulates all resource management actions.

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

public final class ReentrantLockAction {
  private staticwhether {{str}} is {{null}}, a runtime exception in this component may prevent the lock from being released.


h2. Compliant Solution

This compliant solution adds a {{finally}} block and moves the {{unlock()}} call into it. 

{code:bgColor=#ccccff}
final class DateHandler {
  private final Date date = new Date();
  final Lock lock = new ReentrantLock();

  public static void doSomethingSafely(String strdoSomething(File file, LockAction action)  {
    InputStream in = null;
    lock.lock();
    try {
      in = new FileInputStream(file);
  doSomething(str    action.doSomethingWithFile(in);
    } catch (ThrowableFileNotFoundException tfnf) {
      // Forward to handler
    } finally {
    }  lock.unlock();

   public   voidif doSomething(String strin != null) {
    try {
   try {
  lock.lock();
      String dateString = datein.toStringclose();
       if } catch (str.equals(dateString)IOException e) {
          // ...
Forward to handler
    }
    } finally {
      lock.unlock();}
    }
  }
}
{code}

Consequently, the lock is released successfully even in the event of a runtime exception. 


h2. Exceptions

*EX1* : Intrinsic locks of class objects are associated with the use of the {{synchronized}} keyword, and are automatically released on exceptional conditions such as abnormal thread termination.


h2. Risk Assessment

Failing to release a lock on an exceptional condition may lead to thread starvation and deadlock.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON15- J | low | likely | low | {color:#cc9900}{*}P9{*}{color} | {color:#cc9900}{*}L2{*}{color} |



h3. Automated Detection

TODO


h3. Related Vulnerabilities

[GERONIMO-2234|http://issues.apache.org/jira/browse/GERONIMO-2234]

h2. References

\[[API 06|AA. Java References#API 06]\] Class {{ReentrantLock}}

----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|VOID CON14-J. Ensure atomicity of 64-bit operations]      [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)]      [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON16-J. Do not expect sleep(), yield() and getState() methods to have any synchronization semantics]


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
      }
    });
  }
}

Noncompliant Code Example (Unchecked Exception)

This noncompliant code example uses a ReentrantLock to protect a java.util.Date 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();
  }
}

A runtime exception can occur because the doSomething() method fails to check whether str is a null reference, preventing the lock from being released.

Compliant Solution (finally Block)

This compliant solution encapsulates all operations that can throw an exception in a try block and releases the lock in the associated finally block. Consequently, the lock is released even in the event of a runtime exception.

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();
    }
  }
}

The doSomething() method also avoids throwing a NullPointerException by ensuring that the string does not contain a null reference.

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

LCK08-J

Low

Likely

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. Furthermore, the server cannot be restarted because the lock is never cleared.

Related Guidelines

Bibliography


...

Image Added Image Added Image Added