4 ms·
That's not accurate for a final field, as final fields are initialized in a special way. https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.html#jls-17.
by charleslmunger 2y ago
That's not accurate for a final field, as final fields are initialized in a special way.
https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.html#jls-17.5 https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.ht...
>An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.
If you don't publish a reference to the object from within the constructor, you will not see a null value of the final field, even if the object itself was unsafely published across threads via a non-volatile field.
- kbolino 2y agoThis too is thanks to JSR-133. In fact, it seems that, thanks to this part of JSR-133, what I said above about marking shared volatile is actually unnecessary. There must be a memory barrier somewhere, under the hood, though.
- charleslmunger 2y agoAt least on android arm64, looks like a `dmb ishst` is emitted after the constructor, which allows future loads to not need an explicit barrier. Removing `final` from the field causes that barrier to not be emitted. https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:android-java,selection:(endColumn:6,endLineNumber:9,positionColumn:6,positionLineNumber:9,selectionStartColumn:6,selectionStartLineNumber:9,startColumn:6,startLineNumber:9),source:'//+Type+your+code+here,+or+load+an+example.%0Aclass+Square+%7B%0A++++static+Foo+foo%3B%0A++++static+Bar+square(int+num)+%7B%0A++++++++return+foo.bar%3B%0A++++%7D%0A++++static+void+circle(Bar+bar)+%7B%0A++++++++foo+%3D+new+Foo(bar)%3B%0A++++%7D%0A++++static+final+class+Foo+%7B%0A++++++++final+Bar+bar%3B%0A++++++++public+Foo(Bar+bar)+%7B%0A++++++++++++this.bar+%3D+bar%3B%0A++++++++%7D%0A++++%7D%0A++++static+final+class+Bar+%7B%7D%0A%7D%0A%0A'),l:'5',n:'0',o:'Android+Java+source+%231',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:java-dex2oat-latest,filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'0',trim:'1',verboseDemangling:'0'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:1,lang:android-java,libs:!(),options:'',overrides:!(),selection:(endColumn:17,endLineNumber:42,positionColumn:16,positionLineNumber:42,selectionStartColumn:17,selectionStartLineNumber:42,startColumn:16,startLineNumber:42),source:1),l:'5',n:'0',o:'+ART+dex2oat+latest+(Editor+%231)',t:'0')),k:50,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4 https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename...