Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Often Will Java Sync To Main Memory?

I have a set of counters which will only ever be updated in a single thread.

If I read these values from another thread and I don't user volatile/atomic/synchronized how out of date can these values be?

I ask as I am wondering if I can avoid using volatile/atomic/synchronized here.

I currently believe that I can't make any assumptions about time to update (so I am forced to use at least volatile). Just want to make sure I am not missing something here.

like image 861
Gareth Avatar asked May 13 '26 18:05

Gareth


2 Answers

I ask as I am wondering if I can avoid using volatile/atomic/synchronized here.

In practice, the CPU cache is probably going to be synchronized to main memory anyway on a regular basis (how often depends on many parameters), so it sounds like you would be able to see some new values from time to time.

But that is missing the point: the actual problem is that if you don't use a proper synchronization pattern, the compiler is free to "optimise" your code and remove the update part.

For example:

class Broken {
    boolean stop = false;

    void broken() throws Exception {
        while (!stop) {
            Thread.sleep(100);
        }
    }
}

The compiler is authorised to rewrite that code as:

void broken() throws Exception {
    while (true) {
        Thread.sleep(100);
    }
}

because there is no obligation to check if the non-volatile stop might change while you are executing the broken method. Mark the stop variable as volatile and that optimisation is not allowed any more.

Bottom line: if you need to share state you need synchronization.

like image 85
assylias Avatar answered May 16 '26 09:05

assylias


How stale a value can get is left entirely to the discretion of the implementation -- the spec doesn't provide any guarantees. You will be writing code that depends on the implementation details of a particular JVM and which can be broken by changes to memory models or to how the JIT reorders code. The spec seems to be written with the intent of giving the implementers as much rope as they want, as long as they observe the constraints imposed by volatile, final, synchronized, etc.

like image 25
Nathan Hughes Avatar answered May 16 '26 09:05

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!