Why is this code working without volatile?

前端 未结 2 1260
广开言路
广开言路 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:32

    The volatile keyword guarantees that changes are visible amongst multiple threads, but you're interpreting that to mean that opposite is also true; that the absence of the volatile keyword guarantees isolation between threads, and there's no such guarantee.

    Also, while your code example is multi-threaded, it isn't necessarily concurrent. It could be that the values were cached per-thread, but there was enough time for the JVM to propagate the change before you printed the result.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题