How to check the visibility of values ​​between threads

What is the best way to check the visibility of values ​​between threads?

class X {
 private volatile Object ref;

 public Object getRef() {
  return ref;
 }

 public void setRef(Object newRef) {
  this.ref = newRef;
 }
}

Class X provides an object reference ref. If parallel threads read and write an object reference, each thread should see the last object that was installed. The modifier volatilemust do this. The implementation here is an example that can also be synchronized or implemented based on locking.

Now I'm looking for a way to write a test that tells me when the visibility of the value does not match the specified one (older values ​​were read).

Well, if the test really burns some processor cycles.

+3
5

JLS , , , " ". , . , , JVM, , , ... , .

, . , . (-) , , .


:

, () JDK 1.4.2 (rev 12)/Linux/32bit JVM x, y, z, . 1000 , , , volatile. ?

  • , ? , .., . , .
  • , ; Java, .
  • , volatile.

-, . , , ... .. : -)


: . , . , : 1) 2) , JIT ( ...)

+2

, , , , .

, . jvm .

, unit test , volatile, .

+2

, , . , ?

class Wrapper {
    private X x = new X();
    private volatile Object volatileRef;
    private final Object setterLock = new Object();
    private final Object getterLock = new Object();

    public Object getRef() {
        synchronized(getterLock) {
            Object refFromX = x.getRef();
            if (refFromX != volatileRef) {
                // FAILURE CASE!
            }
            return refFromX;
        }
    }

    public void setRef(Object ref) {
        synchronized(setterLock) {
            volatileRef = ref;
            x.setRef(ref);
        }
    }
}

? , , , , .

+1

?

public class XTest {

 @Test
 public void testRefIsVolatile() {
  Field field = null;
  try {
   field = X.class.getDeclaredField("ref");
  } catch (SecurityException e) {
   e.printStackTrace();
   Assert.fail(e.getMessage());
  } catch (NoSuchFieldException e) {
   e.printStackTrace();
   Assert.fail(e.getMessage());
  }
  Assert.assertNotNull("Ref field", field);
  Assert.assertTrue("Is Volatile", Modifier.isVolatile(field
    .getModifiers()));
 }

}

0

, : , , , , ?

, , , . JVM, , . . . , , . , . , , , . , - . , , , .

, . unit test, , , , . unit test , , , , . , , , . , , . .

0

Source: https://habr.com/ru/post/1717496/


All Articles