Method chaining is a technique that defines several methods that return the this
reference of the current object. It is a convenience mechanism that allows multiple method invocations on the same object to occur, in a single statement. However, unless special care is taken, the implementation may not be safe for multithreaded use.
Noncompliant Code Example
Several design patterns exist for building an object and setting its optional fields. However, not all of them provide initialization safety, in that, a thread may observe the object before its construction is over. This noncompliant code example shows the unsafe Javabeans pattern.
...
The Javabeans pattern uses a no-argument constructor along with a series of parallel setter methods to build an object. This pattern is not thread-safe and can lead to inconsistent object state. Moreover, it permits another thread to access the object even though it may only be partially initialized (not all required fields are initialized).
Compliant Solution
Wiki Markup |
---|
This compliant solution uses the Builder pattern's \[[Gamma 95|AA. Java References#Gamma 95]\] variant suggested by Bloch \[[Bloch 08|AA. Java References#Bloch 08]\] to ensure thread safety and atomicity of object creation. |
...
If the number of fields is small, it is better to synchronize the setter methods instead of using this design pattern.
Risk Assessment
Using implementations of method chaining that are not thread-safe can lead to non-deterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON30- J | low | unlikely | high | P1 | L1 |
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 7, Avoid finalizers |
...