Why is this code working without volatile?

前端 未结 2 1259
广开言路
广开言路 2021-01-13 13:56

I am new to Java, I am currently learning about volatile. Say I have the following code:

public class Test
{
    private static boolean b = fals         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 14:43

    You are right that with volatile, you can ensure/guarantee that your 2 threads will see the appropriate value from main memory at all times, and never a thread-specific cached version of it.

    Without volatile, you lose that guarantee. And each thread is working with its own cached version of the value.

    However, there is nothing preventing the 2 threads from resynchronizing their memory if and when they feel like it, and eventually viewing the same value (maybe). It's just that you can't guarantee that it will happen, and you most certainly cannot guarantee when it will happen. But it can happen at some indeterminate point in time.

    The point is that your code may work sometimes, and sometimes not. But even if every time you run it on your personal computer, is seems like it's reading the variable properly, it's very likely that this same code will break on a different machine. So you are taking big risks.

提交回复
热议问题