• Post Reply Bookmark Topic Watch Topic
  • New Topic

Final members in nonimmutable objects - thread safe?

 
Warren Dew
blacksmith
Ranch Hand
Posts: 1332
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, the following is thread safe due to immutability:


And the following is safe due to synchronization:

Now consider the following class:

Two questions:

1. Is this thread safe?

2. Can someone point to the relevant part of the Java Language Specification?

The reason I ask is that I can only find comments about "final" ensuring thread safety in the context of immutable objects, by ensuring a store barrier before exiting the constructor. Is such a barrier ensured even if only some of the member data is final? Does the barrier come at the end of the constructor, or might it occur before the initialization of nonfinal members?

(Edited to remove an unintended "synchronized" before the accessor of the final variable in the Mixed class.)
[ October 22, 2008: Message edited by: Warren Dew ]
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Yes.

2. JLS 17.5 discusses the effect of using final using an example class that has one final field and one nonfinal field. The class may look immutable, but it's not, because of the nonfinal field. Nonetheless the discussion makes the point that the final field is thread-safe, even though the nonfinal field is not. They don't specifically talk about synchronization here, but the point remains that you can evaluate the thread safety of different fields separately, and use different strategies for each.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!