Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On the thread safety of instance variable initialization

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?

like image 451
non sequitor Avatar asked Oct 14 '09 20:10

non sequitor


People also ask

Are instance variables thread-safe?

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.

Is static initialization thread-safe?

Starting in C++11, scoped static initialization is now thread-safe, but it comes with a cost: Reentrancy now invokes undefined behavior.] The rule for static variables at block scope (as opposed to static variables with global scope) is that they are initialized the first time execution reaches their declaration.

What does it mean to initialize an instance variable?

Instance variables are initialized when the class is instantiated. If instance variables are declared only and not initialized, they will be assigned default values by JVM before constructor execution.


2 Answers

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.

like image 56
JaakkoK Avatar answered Nov 10 '22 00:11

JaakkoK


since your variables are instance variables, not class variables, you don't have a thread safety issue during initialization using either method. I'm sure others will chime in if there's a Java-standard-recommended best practice.

like image 32
atk Avatar answered Nov 09 '22 23:11

atk