• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Final members in nonimmutable objects - thread safe?

 
blacksmith
Posts: 1332
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Rancher
Posts: 5088
82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I am not a spy. Definitely. Definitely not a spy. Not me. No way. But this tiny ad ...
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic