Reputation: 683
I am trying to fix an issue which says
Lazy initialization of "static" fields should be "synchronized"
suggested by findbug
.This link suggests that either I have to make the field variable volatile
or make the initialization block synchronized
. Which way is better? What are pros and cons of each approach?
Upvotes: 1
Views: 4986
Reputation: 140457
There is no better.
There are simply a few different patterns how to solve this problem. See here for a complete discussion of that topic.
In that sense: for a newbie doing first steps, simply go with a synchronized
method. For "professional" use - see the above link; and determine which of the solutions given there best fits your needs.
Upvotes: 2
Reputation: 470
In your example you should use synchronized
because volatile
does not guarantee atomicity.
If you use volatile
you can initialize several instances of the object.
Upvotes: 0