...
Programs must ensure that threads that hold locks on other objects release those locks appropriately before entering the wait state. Additional guidance on waiting and notification is available in THI03-J. Always invoke wait() and await() methods inside a loop and THI02-J. Notify all waiting threads rather than a single thread.
Noncompliant Code Example (Network I/O)
...
Code Block | ||
---|---|---|
| ||
// No synchronization public boolean sendPage(Socket socket, String pageName) { Page targetPage = getPage(pageName); if (targetPage == null){ return false; } return deliverPage(socket, targetPage); } // Requires synchronization private synchronized Page getPage(String pageName) { Page targetPage = null; for (Page p : pageBuff) { if (p.getName().equals(pageName)) { targetPage = p; } } return targetPage; } // Return false if an error occurs, true if successful public boolean deliverPage(Socket socket, Page page) { ObjectOutputStream out = null; boolean result = true; try { // Get the output stream to write the Page to out = new ObjectOutputStream(socket.getOutputStream()); // Send the page to the client out.writeObject(page);out.flush(); } catch (IOException io) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; } |
Exceptions
LCK09-J-EX0: Classes that provide an appropriate termination mechanism to callers are permitted to violate this rule (see THI04-J. Ensure that threads performing blocking operations can be terminated).
LCK09-J-EX1: Methods that require multiple locks may hold several locks while waiting for the remaining locks to become available. This constitutes a valid exception, although the programmer must follow other applicable rules, especially LCK07-J. Avoid deadlock by requesting and releasing locks in the same order to avoid deadlock .
Automated Detection
Some static analysis tools are capable of detecting violations of this rule.
...
...
CCE_LK_LOCKED_BLOCKING_CALLS
...
Risk Assessment
Blocking or lengthy operations performed within synchronized regions could result in a deadlocked or unresponsive system.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
LCK09-J | Low | Probable | High | P2 | L3 |
Automated Detection
Some static analysis tools are capable of detecting violations of this rule.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.CONCURRENCY.STARVE.BLOCKING | Blocking in Critical Section (Java) | ||||||
Parasoft Jtest |
| CERT.LCK09.TSHL CERT.LCK09.TSHL2 | Do not use blocking methods while holding a lock Do not call 'Thread.sleep()' while holding a lock since doing so can cause poor performance and deadlocks | |||||||
PVS-Studio |
| V6095 | |||||||
ThreadSafe |
| CCE_LK_LOCKED_BLOCKING_CALLS | Implemented | ||||||
SonarQube |
| S2276 | Implemented |
Related Guidelines
Bibliography
...
...