Java Interview Question

Use this advanced question and answer to prepare for your next Java interview.

Explain instruction reordering. In what context can instruction reordering create problems? How can it be fixed?


Instruction reordering is when the execution order of the code is changed by the JVM at compile time or run time. This is done to optimize the code. Instruction reordering guarantees program order execution. This means that two statements which are related will have a happens-before relation, but two unrelated statements can be executed out-of-order.

The context where this can cause problems is in a multithreaded environment. There is no program order between threads, so there should be no assumptions on execution order following the code order.

To avoid reordering problems, threads need to be synchronized properly. Code that needs code order execution should be placed in synchronized blocks.

Looking for developers?

Want to learn more about Gigster? Enter your email and we'll be in touch.