Method chaining is a convenient mechanism that allows multiple method invocations on the same object to occur in a single statement. A method-chaining implementation consists of a series of methods that return the
this reference. This implementation allows a caller to invoke methods in a chain by performing the next method invocation on the return value of the previous method in the chain.
Although the methods used in method chaining can be atomic, the chain they comprise is inherently nonatomic. Consequently, callers of methods that are involved in method chaining must provide sufficient locking to guarantee that the entire chain of invocations is atomic, as shown in VNA03-J. Do not assume that a group of calls to independently atomic methods is atomic.
Noncompliant Code Example
Method chaining is a useful design pattern for building an object and setting its optional fields. A class that supports method chaining provides several setter methods that each return the
this reference. However, if accessed concurrently, a thread may observe shared fields to contain inconsistent values. This noncompliant code example shows the JavaBeans pattern, which is not thread-safe:
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 when the object is modified concurrently. In this noncompliant code example, the client constructs a
USCurrency object and starts two threads that use method chaining to set the optional values of the
USCurrency object. This example code might result in the
USCurrency instance being left in an inconsistent state, for example, with two quarters and one dime or one quarter and two dimes.
Builder.newInstance() factory method is called with any required arguments to obtain a
Builder instance. The optional parameters are set using the setter methods of the builder. The object construction concludes with the invocation of the
build() method. This pattern makes the
USCurrency class immutable and consequently thread-safe.
Note that the
currency field cannot be declared final because it is assigned a new immutable object. It is, however, declared volatile in compliance with VNA01-J. Ensure visibility of shared references to immutable objects.
When input must be validated, ensure that the values are defensively copied prior to validation (see OBJ06-J. Defensively copy mutable inputs and mutable internal components for more information). The
Builder class also complies with OBJ08-J. Do not expose private members of an outer class from within a nested class because it maintains a copy of the variables defined in the scope of the containing class. The private members within the nested class take precedence and, as a result, maintain encapsulation.
Using method chaining in multithreaded environments without performing external locking can lead to nondeterministic behavior.