原文: 第四章







What is meant by reordering?

There are a number of cases in which accesses to program variables (object instance fields, class static fields, and array elements) may appear to execute in a different order than was specified by the program. The compiler is free to take liberties with the ordering of instructions in the name of optimization. Processors may execute instructions out of order under certain circumstances. Data may be moved between registers, processor caches, and main memory in different order than specified by the program.

For example, if a thread writes to field a and then to field b, and the value of b does not depend on the value of a, then the compiler is free to reorder these operations, and the cache is free to flush b to main memory before a. There are a number of potential sources of reordering, such as the compiler, the JIT, and the cache.

The compiler, runtime, and hardware are supposed to conspire to create the illusion of as-if-serial semantics, which means that in a single-threaded program, the program should not be able to observe the effects of reorderings. However, reorderings can come into play in incorrectly synchronized multithreaded programs, where one thread is able to observe the effects of other threads, and may be able to detect that variable accesses become visible to other threads in a different order than executed or specified in the program.

Most of the time, one thread doesn’t care what the other is doing. But when it does, that’s what synchronization is for.

原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: Java内存模型FAQ(四)重排序意味着什么?

徐 飞


Latest posts by 徐 飞 (see all)

  • Trackback are closed
  • Comments (2)
    • Anonymous
    • 04/24. 2014 5:15pm


    • ethanswan
    • 02/18. 2016 11:03pm


You must be logged in to post a comment.

return top