...
Method chaining should not be used in a multithreaded environment because chained invocations of a set of methods are non-atomic and, consequently, noncompliant with CON07-J. Do not assume that a group of calls to independently atomic methods is atomic.
Noncompliant Code Example
Method chaining is useful for building an object and setting its optional fields. However, in a multithreaded environment, a thread may observe shared fields to contain inconsistent values. This noncompliant code example shows the Javabeans pattern which is not safe for multithreaded use.
...
The Javabeans pattern uses a no-argument constructor and a series of parallel setter methods to build an object. This pattern is not thread-safe and can lead to inconsistent object state. In this example, a client that constructs a USCurrency
object and starts two threads as shown may find the object to contain two quarters and one dime or one quarter and two dimes, contrary to what it expects.
Compliant Solution
Wiki Markup |
---|
This compliant solution uses the variant of the Builder pattern \[[Gamma 95|AA. Java References#Gamma 95]\] suggested by Bloch \[[Bloch 08|AA. Java References#Bloch 08]\] to ensure thread safety and atomicity of object creation. |
...
If input needs to be validated, ensure that the values are defensively copied prior to the validation (see FIO00-J. Defensively copy mutable inputs and mutable internal components for more information). The builder class does not violate SCP03-J. Do not expose sensitive private members of the outer class from within a nested class because it maintains a copy of the variables defined in the scope of the containing class. These take precedence and as a result, do not break encapsulation.
Exceptions
EX1: A class may use method chaining in a multithreaded environment if it sufficiently documents this fact. Client code must externally use some locking to ensure that the method calls are thread-safe.
Risk Assessment
Using method chaining in multithreaded environments without performing external locking can lead to non-deterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON30- J | low | probable | medium | P4 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] \[[Bloch 08|AA. Java References#Bloch 08]\] Item 2: "Consider a builder when faced with many constructor parameters" |
...