jvm reordering/visibility effect test

不羁岁月 提交于 2019-12-05 10:17:10

Here is a nice article which should show reordering on x86 (quite a feat because the x86 memory model is pretty much "safe"):

http://bartoszmilewski.wordpress.com/2008/11/05/who-ordered-memory-fences-on-an-x86/

Your example will not show reordering. The compiler will not reorder to "store object reference after allocation but before construction" because the constructor could throw and thus the reference would need to be reverted. Some Processors may reorder this, but no intel compatible ones, due to the given guaranties.

Re-ordering is not guaranteed. It usually only occurs when the JIT determines there might be a performance gain.

In your case, what you are looking for is not re-ordering but an Object which doesn't appear to have been correctly initialised.

Your objects are highly likely to use a new memory location each time (or at least one which is not in cache) On x86/x64 architectures, I have found that the cache will always be correct the first time it has to load memory when was updated by another thread.

re-ordering does not necessarily happen. and when it does, it's hard to observe. you sample size of 100 is too tiny. Try a billion for starters.

Suppose re-ordering happens, at the time of write, reference is assigned first, then fields are populated. Your read process reads the reference first, then reads the fields. So write and read follow the same order, it's almost impossible for read to catch up and get ahead of write.

You can address the issue by

  1. pause in constructor (therefore pause in write)
  2. write and read fields in opposite direction

Still, reordering may not occur and you won't be able to observe it.

could you try to declare sharedArray as non-volatile? It seems to me that handing a volatile reference to a correctly constructed object is safe.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!