judent judent - 5 months ago 7
Java Question

Why processors and compilers need a reordering?

I studied Java Memory Model and faced with re-ordering problem. The simple example:

boolean first = false;
boolean second = false;

void setValues() {
first = true;
second = true;
}

void checkValues() {
while(!second);
assert first;
}


Reordering is very unpredictable and weird. Also, it ruins abstractions. I suppose, that processor's architectures should have a strong reason to do it. So what the reasons?

There is a lot of information about how to handle reordering, but I can't find anything about why it is needed. Everywhere people just say something like "it is because of some performance benefits". What are the performance benefits in store variable second before first, for example?

Can you recommend some article, paper or book about this, or explain it by yourself?

Answer

Imagine to have the following code:

a = 1;
b = 1;
a = a + 1;   // Not present in the register
b = b + 1;   // Not present in the register
a = a + 1;   // Not present in the register
b = b + 1;   // Not present in the register
// Here both a and b has value 3

A possible optimization using memory reorder is

a = 1;
a = a + 1;   // Already in the register
a = a + 1;   // Already in the register
b = 1;
b = b + 1;   // Already in the register
b = b + 1;   // Already in the register
// Here both a and b has value 3

The performance is better because the data are presents in the register.

Note that there are many different levels of optimization, but this will give you an idea why reordering can improve performances.

Comments