On the thread safety of instance variable initialization

java, thread-safety

Solution

Thread safety isn't an issue because this happens at construction phase, and two threads cannot be constructing the same object. Well, if you let `this` escape from the constructor, it might be possible for another thread to access the object during construction, but you really shouldn't do that. Functionality-wise, the two options are the same, so even if there were thread-safety issues, they would affect both the same way.

The first option, of initializing the fields at their declaration, is not always possible if you need to do some computation that cannot be done in an initializer (even then, you can keep the initialization out of the constructor if you do it in an initializer block, though). But if either way is possible, then it's purely a style issue, and I don't think there is a clear preference among Java programmers, so go with whichever seems better to you.

Problem

I see this idiom of initializing instance variables quite a bit ``` public class Test{ private Long l = 1l; private MyClass mc = new MyClass(); public Test(){} ... } ``` But I would prefer ``` public class Test{ private Long l; private MyClass mc; public Test(){ l = 1l; mc = new MyClass(); } ... } ``` Considering that these are non-final variables, are the 2 approaches equivalent or is one "more" correct than the other in terms of thread safety?

Original source