Java – if you have only one write thread, do you need special concurrency?
Assumptions:
>Only one specific thread can set a reference field (not long or double, so writing it is atomic) > any number of threads may read the same field > slightly outdated readings are acceptable (up to a few seconds)
In this case, do you need volatile or atomicreference or anything like that?
This article status:
It seems that you really don't need to do anything special in the situation I describe
So this is a test with curious results:
Sometimes running it will output "thread complete" and then hang permanently Sometimes it's done So the thread sees the changes made by the main thread, but obviously main doesn't always see the changes made by the thread
If I put the system in, or thread In yield, it is called randomly, or just writenbythread volatile, which will be completed every time (10 attempts)
Does this mean that the blog I quoted above is incorrect? Even in a single writer scene, you must have memory impairment?
No one quite answers this question, so I think I will guess that memory barrier is not necessary and may be correct, but nothing can create the relationship before it happens. Java compiler and hotspot can be optimized (such as promotion) so that it will not do anything you want
Solution
The problem is caching on a multi-core system - there is no volatile forced relationship (memory barrier) like volatile. You can have your writing thread write a copy of the variable in the cache at its core, and all reader threads read another and copy the variable on another core Another question is atomicity, and another answer is this