Reputation: 1660
I have a question about visibility in java. The visibility can only appear if we have at least two threads, which run on at least 2 cpu cores . It that right ? Every core can cache variables in its regiresters and cache memory and because of that visibility problems can appear. But what if we have n threads and they all run in one cpu core (of couse, we can not be sure that they will run on only 1 core, but assume that it is possible to achieve that), than there is no way to have memory visibility ? Or this is not right ? Thanks in advance.
Upvotes: 1
Views: 299
Reputation: 12022
If by visibility you refer to shared memory, so that objects that are created or altered in one thread may be visible in another thread, then it does not matter how many cores there are, the visibility will remain the same. Java makes promises as per the Java Language Specification, specifically the Java Memory Model, that must be followed regardless of how many cores.
But what if we have n threads and they all run in one cpu core (of couse, we can not be sure that they will run on only 1 core, but assume that it is possible to achieve that), than there is no way to have memory visibility ? Or this is not right ?
Yes the visibility (shared memory) still exists if there are n threads running on one core. But there are some caveats that exist regardless of how many core. Mainly that each thread has its own cached memory and a variable may have different values across both threads. If the variable is volatile
, then the value of that variable will always get updated across all threads.
A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).
I recommend you read up more on the Java Memory Model.
Upvotes: 2
Reputation: 35096
Even on 1 core running multiple threads, you can still have what you are calling this "visibility" problem, as threads that have loaded a value from memory into a register will save this value to that thread's stack, and will not see the update if the thread is switched off then switched back on again unless the variable / memory is declared volatile
Upvotes: 5