Multi-thread state visibility in Java: is there a way to turn the JVM into the worst case scenario?

后端 未结 7 1653
轻奢々
轻奢々 2021-02-04 08:36

Suppose our code has 2 threads (A and B) have a reference to the same instance of this class somewhere:

public class MyValueHolder {

    private int value = 1;
         


        
7条回答
  •  半阙折子戏
    2021-02-04 09:20

    The example you have given is described as Incorrectly Synchronized in http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4. I think this is always incorrect and will lead to bugs sooner or later. Most of the times later :-).

    To find such incorrectly synchronized code blocks, I use the following algorithm:

    Record the threads for all field modifications using instrumentation. If a field is modified by more than one thread without synchronization, I have found a data race.

    I implemented this algorithm inside http://vmlens.com, which is a tool to find data races inside java programs.

提交回复
热议问题