...
Code Block | ||
---|---|---|
| ||
class Foo { private Helper helper; public Helper getHelper() { return helper; } public void initializesetHelper(int num) { helper = new Helper(num); } } |
...
Because the Helper
class is immutable, it cannot be changed after it is initialized setHelperd and is therefore thread-safe.
However, because the helper
field of class Foo
is not properly synchronized, it is possible that the Foo.getHelper()
method will return a reference to a partially or incorrectly initialized setHelperd helper
object, if invoked from a separate thread.
...
This compliant solution synchronizes the methods of class Foo
to ensure that no thread sees a partially initialized setHelperd helper
field.
Code Block | ||
---|---|---|
| ||
class Foo { private Helper helper; public synchronized Helper getHelper() { return helper; } public synchronized void initializesetHelper(int num) { helper = new Helper(num); } } |
...
Code Block | ||
---|---|---|
| ||
class Foo { private volatile Helper helper; public Helper getHelper() { return helper; } public void initializesetHelper(int num) { helper = new Helper(num); } } |
...