Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
An exceptional condition can circumvent the release of a lock, leading to deadlock. According to the Java API \[[API 06|AA. Java References#API 06]\]:

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

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

h2. Noncompliant Code Example (Checked Exception)

This noncompliant code example protects a resource using a {{ReentrantLock}} but fails to release the lock if an exception occurs while performing operations on the open file. If an exception is thrown, control transfers to the {{catch}} block and the call to {{unlock()}} is not executed.

{code:bgColor=#FFcccc}
public final class Client {
  public void doSomething(File file) {
    final Lock lock = new ReentrantLock();
    try {
      lock.lock();
      InputStream in = new FileInputStream(file);
      // Perform operations on the open file
      lock.unlock();
    } catch (FileNotFoundException fnf) {
      // Handle the exception
    }
  }
}
{code}

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

This noncompliant code example does not close the input stream and consequently, also violates [FIO06-J. Ensure all resources are properly closed when they are no longer needed].


h2. Compliant Solution ({{finally}} block)

This compliant solution encapsulates operations that may throw an exception in a {{try}} block immediately after acquiring the lock.  The lock is acquired just before the try block, which guarantees that it is held when the finally block executes. The lock is released in the corresponding {{finally}} block, which ensures the lock is released regardless of whether or not an exception occurs.

{code:bgColor=#ccccff}
public final class Client {
  public void doSomething(File file) {
    final Lock lock = new ReentrantLock();
    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}

h2. Compliant Solution (Execute-around Idiom)

The execute-around idiom provides a generic mechanism to perform resource allocation and clean-up 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 acquisition and release of locks or open and close operations of files. The {{ReentrantLockAction}} class encapsulates all resource management actions.

{code:bgColor=#ccccff}
public interface LockAction {
  void doSomethingWithFile(InputStream in);
}

public final class ReentrantLockAction {
  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
      }
    });
  }
}
{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. The {{doSomethingSafely()}} method must catch {{Throwable}} to comply 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 DateHandler {
  private final Date date = new Date();
  final Lock lock = new ReentrantLock();

  public void doSomethingSafely(String str) {
    try {
      doSomething(str);
    } catch(Throwable t) {
      // Forward to handler
    }
  }

  public void doSomething(String str) {
    lock.lock();
    String dateString = date.toString();
    if (str.equals(dateString)) {
      // ...
    }
    lock.unlock();
  }
}
{code}

Because the {{doSomething()}} method fails to check if {{str}} is {{null}}, a runtime exception can occur, preventing the lock from being released.


h2. Compliant Solution ({{finally}} block)

This compliant solution encapsulates all operations that can throw an exception in a try block and release the lock in the associated {{finally}} block.  

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

  public void doSomethingSafely(String str) {
    try {
      doSomething(str);
    } catch(Throwable t) {
      // Forward to handler
    }
  }

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

Consequently, the lock is released even in the event of a runtime exception. The {{doSomething()}} method also ensures that the string is not null to avoid throwing a {{NullPointerException}}.


h2. Risk Assessment

Failing to release locks on exceptional conditions 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!|CON13-J. Do not use Thread.stop() to terminate threads]      [!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 assume that the sleep(), yield() or getState() methods provide synchronization semantics]