An exceptional condition can circumvent the release of a lock, leading to deadlock. According to the Java API \ [[API 2006|AA. Bibliography#API 06]\API 2014]: Wiki Markup
A
ReentrantLock
is owned by the thread last successfully locking, but not yet unlocking it. A thread invokinglock
will return, successfully acquiring the lock, when the lock is not owned by another thread.
Consequently, an unreleased lock in any thread will stop 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 using a ReentrantLock
but , an open file, by using a ReentrantLock
. However, the method fails to release the lock if when an exception occurs while performing operations on the open file. If When an exception is thrown, control transfers to the the catch
block block and the call to to unlock()
is not executed never executes.
Code Block | ||
---|---|---|
| ||
public final class Client { private final Lock lock = new ReentrantLock(); public void doSomething(File file) { finalInputStream Lockin lock = new ReentrantLock()null; try { lock.lock(in = new FileInputStream(file); InputStream in = new FileInputStream(filelock.lock(); // Perform operations on the open file lock.unlock(); } catch (FileNotFoundException fnfx) { // Handle the exception exception } finally { if (in != null) { try { in.close(); } catch (IOException x) { // Handle exception } } } |
Note that the lock is not released, even when the doSomething()
method returns.
...
}
} |
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 | ||
---|---|---|
| ||
public final class Client {
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
}
}
}
}
}
|
Compliant Solution (finally
Block)
This compliant solution encapsulates operations that may 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. Invoking Lock.unlock()
in the finally
block ensures that the lock is released, regardless of whether or not an exception occurs.
Code Block | ||
---|---|---|
| ||
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 } } } } } |
Compliant Solution (Execute-
...
Around Idiom)
The execute-around idiom provides a generic mechanism to perform resource allocation and clean-up 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 | ||
---|---|---|
| ||
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 that java.util.Date
instance, which is not thread-safe unsafe by design. The doSomethingSafely()
method must catch Throwable
to comply with guideline EXC06-J. Do not allow exceptions to transmit sensitive information.
Code Block | ||
---|---|---|
| ||
final class DateHandler { private final Date date = new Date(); private final Lock lock = new ReentrantLock(); public void doSomethingSafely(String str) { try { doSomething(str); } catch(Throwable t) { // Forwardstr tocould handler } } be null public void doSomething(String str) { lock.lock(); String dateString = date.toString(); if (str.equals(dateString)) { // ... } // ... lock.unlock(); } } |
Because A runtime exception can occur because the doSomething()
method fails to check if whether str
is a null reference, a runtime exception can occur, preventing the lock from being released.
...
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 | ||
---|---|---|
| ||
final class DateHandler { private final Date date = new Date(); private final Lock lock = new ReentrantLock(); public void doSomethingSafely(String str) { try { doSomething(str); } catch(Throwable t) { // Forwardstr tocould handler } } be null public void doSomething(String str) { lock.lock(); try { String dateString = date.toString(); if (str != null && str.equals(dateString)) { // ... } // ... } finally { lock.unlock(); } } } |
Consequently, the lock is released even in the event of a runtime exception. The doSomething()
method also ensures avoids throwing a NullPointerException
by ensuring that the string is does not null to avoid throwing a NullPointerException
contain a null reference.
Risk Assessment
Failing Failure to release locks on exceptional conditions may could lead to thread starvation and deadlock.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
LCK08-J |
Low |
Likely |
Low | P9 | L2 |
References
Wiki Markup |
---|
\[[API 2006|AA. Bibliography#API 06]\] Class {{ReentrantLock}} |
Automated Detection
TODO
Related Vulnerabilities
Automated Detection
Some static analysis tools are capable of detecting violations of this rule.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.LCK08.RLF CERT.LCK08.LOCK | Release Locks in a "finally" block Do not abandon unreleased locks | ||||||
ThreadSafe |
| 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
...
12. Locking (LCK) LCK09-J. Do not perform operations that may block while holding a lock