Most likely, you have your own answer, but I just want to add my explanation.
For an object (for your case) to be thread safe, it must:
- Stay unchanged
- Be well posted
Immutable - you did it like that. Cannot change the panel after installing it. This is pretty obvious.
Safe publishing . According to an example, the code is not published securely. Since the bar is not final, the compiler can freely reorder it at its discretion. The compiler can publish (write to main memory) a link to the Foo instance before writing to bar. This would mean that bar is null. So, first the link to Foo is written to the main memory, then there is a record in the bar. Between these two events, another thread can see that the stale bar is null.
If you add the final version, JMM will ensure that:
the values ββof the final fields are guaranteed to be visible to other threads accessing the constructed object.
Or the final field prevents reordering. Thus, creating this final variable will ensure thread safety.
Eugene
source share