If a lock is being held and an operation that can block is performed, any other thread that needs to acquire that lock may also block. This condition can degrade system performance or cause a deadlock to occur. Blocking calls include, but are not limited to, network, file, and console I/O.
Using a blocking operation while holding a lock may be unavoidable for a portable solution. For instance, file access could be protected via a lock to prevent multiple threads from mutating the contents of the file. Or, a thread may be required to block while holding one or more locks and waiting to acquire another lock. In these cases, attempt to hold the lock for the least time required. Additionally, if acquiring multiple locks, the order of locking must avoid deadlock, as specified in CON35-C. Avoid deadlock by locking in a predefined order.
Noncompliant Code Example
This noncompliant example calls
fopen() while a mutex is locked. The calls to
fclose() are blocking and may block for an extended period of time if the file resides on a network drive. While the call is blocked, other threads that are waiting for the lock are also blocked.
Compliant Solution (Block while Not Locked)
This compliant solution performs the file operations when the lock has not been acquired. The blocking behavior consequently affects only the thread that called the blocking function.
Blocking or lengthy operations performed within synchronized regions could result in a deadlocked or an unresponsive system.
|Blocking in critical section|
|CERT_C-CON05-a||Do not use blocking functions while holding a lock|
Key here (explains table format and definitions)
|CERT Oracle Secure Coding Standard for Java||LCK09-J. Do not perform operations that can block while holding a lock||Prior to 2018-01-12: CERT: Unspecified Relationship|
|MITRE CWE||CWE-557||Prior to 2018-01-12:|
|MITRE CWE||CWE-662||Prior to 2018-01-12:|