0

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?

aravindkanna
  • 663
  • 1
  • 7
  • 25

2 Answers2

1

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • let's say I have a string declared and is getting initialized which became thread unsafe. For such cases, can I just make the string field volatile so that the value to which it is initialized is available to all threads immediately. – aravindkanna Aug 11 '17 at 08:02
  • *volatile* means that read/writes **always** access the **memory**. Accessing memory is one order of magnitude **slower** compared to accessing something that can reside in a local cache! Thus: yes, sure, volatile solves problems. But it comes at cost. Thus you are **careful** about using it. – GhostCat Aug 11 '17 at 08:07
  • For every instance of this issue, if I use double checked locking idiom, as suggested in the resource you provided, will that be efficient? or making the whole block `synchronized` be efficient? The problem is if I have a large method, where all the instructions can be executed by all threads in parallel, except the initialization statement, making the whole method `synchronized` may effect the efficiency. I think this loss is more than what we face from making it volatile. Correct me if I am wrong. – aravindkanna Aug 11 '17 at 08:18
  • 1
    If you have *one* method doing so many things ... you are probably violating the "single responsibility principle" in the first place. It is impossible to give specific advise on code that we can't read and that was written to implement requirements unknown to us. And beyond that: so you find my input "good enough" to come back with more questions - but you don't deem it worth an upvote? Beyond that: please understand that SO is not a discussion forum where you come back with more and more question in comments. In that sense: consider improving your question ... or asking another one! – GhostCat Aug 11 '17 at 08:29
0

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.

Shchipunov
  • 460
  • 4
  • 11