java - How do final fields prevent other threads from seeing partially constructed objects? -


i looking creating immutable datatype has final fields (including array constructed , filled prior being assigned final member field), , noticed seems jvm specified guarantee other thread gets reference object see initialized fields , array values (assuming no pointers this published within constructor, see what "incompletely constructed object"? , how jvm's implicit memory barriers behave when chaining constructors?).

i curious how achieved without synchronizing every access object, or otherwise paying significant performance penalty. according understanding, jvm can achieve doing following:

  1. issue write-fence @ end of constructor
  2. publish reference new object after write-fence
  3. issue read-fence time refer final field of object

i can't think of simpler or cheaper way of eliminating risk of other threads seeing uninitialized final fields (or recursive references through final fields).

this seems impose severe performance penalty due of read-fences in other threads reading object, eliminating read-fences introduces possibility object reference seen in processor before issues read-fence or otherwise sees updates memory locations corresponding newly initialized final fields.

does know how works? , whether introduces significant performance penalty?

see "memory barriers" section in this writeup.

a storestore barrier required after final fields set , before object reference assigned variable. key piece of info you're asking about.

according "reordering" section there, store of final field can not reordered respect store of reference object containing final field.

additionally, states in v.afield = 1; x.finalfield = v; ... ; sharedref = x;, neither of first 2 can reordered respect third; ensures stores fields of object stored final field guaranteed visible other threads before reference object containing final field stored.

together, means stores final fields must visible threads before reference object containing field stored.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -