简体   繁体   中英

Java concurrency visibility

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.

即使在运行多个线程的1个内核上,您仍然会遇到所谓的“可见性”问题,因为从内存中将值加载到寄存器中的线程会将此值保存到该线程的堆栈中,并且在以下情况下看不到更新:线程被关闭,然后再次打开, 除非变量/内存被声明为volatile

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM