been staring at this volatile keyword stuff for hours and I genuinely cannot figure out where my understanding breaks

Posted by Effective_Celery_515@reddit | learnprogramming | View on Reddit | 3 comments

okay so I've been going through Java concurrency for a few weeks and I thought i finally had a handle on things. understood synchronized, understood locks felt good. then i hit volatile and it seemed straightforward at first just forces reads from main memory instead of cache simple enough.

but then i realized volatile doesn't help you with something like i++ even when the variable is declared volatile.

I know i++ isn't atomic but i still expected visibility guarantees to make things more predictable across threads and apparently that assumption was completely wrong.

I tried tracing through a two thread example on paper and i still couldn't figure out exactly where my mental model is off.

so what is volatile actually promising and what isn't it? I've read the JLS memory model section twice and it honestly reads like a legal document. has anyone found a concrete analogy or a simple scenario that finally made this distinction click?