...
Code Block | ||
---|---|---|
| ||
public class Helper { private final int n; public Helper(int n) { this.n = n; } // other fields & methods, all fields are final } class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) { helper = new Helper(); // If the helper is null, create a new instance } } } return helper; // If helper is non-null, return its instance } } |
Note that if Foo
was mutable, the Helper
field would need to be declared volatile
as shown in CON00-J. Declare shared variables as volatile to ensure visibility and prevent reordering of statements.
Compliant Solution (static initialization)
...