Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMM sequential consistency

I'm trying to understand "sequential consistency" in terms of Java memory model. Definition from JLS, chapter 17 is not that clear to me.

I will give my vision, correct me if I'm wrong. Having program with one thread sequential consistency means that if action1 comes before action2 in the program order, than action2 should see the results of action1.

Having two threads.

Thread1:

action1
action2

Thread2:

action3
action4

If action3 sees the result of action2, than it should see the results of action1 as well.

like image 512
andrershov Avatar asked Jul 28 '26 02:07

andrershov


2 Answers

You are correct; sequential consistency means that each action is executed atomically and is immediately visible to all threads. It is as if you interleaved all threads into a single thread, executing actions one by one.

Be careful to note that sequential consistency is not the way Java Memory Model actually works.

Quote from 17.4.3, Programs and Program Order:

If we were to use sequential consistency as our memory model, many of the compiler and processor optimizations that we have discussed would be illegal.

like image 93
Marko Topolnik Avatar answered Jul 30 '26 20:07

Marko Topolnik


one thread sequential consistency means that if action1 comes before action2 in the program order, than action2 should see the results of action1.

This is correct, without this principle it would be impossible to program.

If action3 sees the result of action2, than it should see the results of action1 as well.

There is no such guarantee without the use of volatile or locking. For example action1 could update one cache line and action2 could update another. When this happens there is no guarantees as to when, or if the second thread will see those changes.

like image 35
Peter Lawrey Avatar answered Jul 30 '26 20:07

Peter Lawrey



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!