Visibility of threads between one process

I’ve been reading Crack Code Interview lately, but one paragraph there confuses me on page 257:

A thread is a specific way to execute a process; when one thread changes a resource of a process, this change is immediately visible to threads of children.

IIRC, if one thread makes a change to a variable, this change will first be stored in the processor cache (say, L1 cache) and does not guarantee synchronization with other threads if the variable is not declared mutable.

I'm right?

+6
source share
2 answers

No, you are mistaken. But this is a very common misunderstanding.

Every modern multi-core processor has hardware cache consistency . L1 and similar caches are invisible. The processor cache, such as the L1 cache, has nothing to do with memory visibility.

Changes are visible immediately when a thread changes a process resource. The problem is optimization, which does not allow changing the process resources in the exact order in which the code is indicated.

If your code has k = j; i = 4; if (j == 2) foo(); k = j; i = 4; if (j == 2) foo(); , the optimizer can see that your first assignment reads the value of j . Therefore, perhaps he would not read it again when you compare it to 2 , since he “knows” that he cannot change. However, another thread may have changed it. Thus, some kinds of optimization should be turned off when synchronization between threads is required. What do things like volatile .

If compilers and processors did not make optimizations and executed the program exactly as it was written, volatile will never be needed. Memory monitoring is code optimization (some of them are executed by the compiler, some by the processor), but not cached.

+9
source

I think the text you are quoting is incorrect . The whole idea of ​​the Java memory model is to cope with complex optimization using modern software and hardware, so that programmers can determine which records are visible by corresponding readings in other threads.

If a program in Java is not properly synchronized, you cannot guarantee that changes in one thread will be immediately visible to other threads. Perhaps the text refers to a very specific (and weak) memory model.

Using mutable variables is just one way to synchronize threads and is not suitable for all scenarios.

- Edit -

I think I understand the confusion now ... I agree with David Schwartz, suggesting that:

1) "changes the process resource" means the actual change of the resource, and not just the execution of a write command written in some high-level computer language.

2) "immediately visible to the sisters' flows" means that other flows can see it; this does not mean that the thread in your program will definitely see it. You still have to use the synchronization tools to turn off optimization, bypassing the actual access to the resource.

+1
source

Source: https://habr.com/ru/post/943797/


All Articles