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.
ref
volatile
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.
JLS , , , " ". , . , , JVM, , , ... , .
, . , . (-) , , .
:
, () JDK 1.4.2 (rev 12)/Linux/32bit JVM x, y, z, . 1000 , , , volatile. ?
-, . , , ... .. : -)
: . , . , : 1) 2) , JIT ( ...)
, , , , .
, . jvm .
, unit test , volatile, .
, , . , ?
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); } } }
? , , , , .
?
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())); }
}
, : , , , , ?
, , , . JVM, , . . . , , . , . , , , . , - . , , , .
, . unit test, , , , . unit test , , , , . , , , . , , . .
Source: https://habr.com/ru/post/1717496/More articles:Independent contracts and non-competitive reservations? - serviceRuby Regular Expressions - ruby | fooobar.comShould I use pgreloaded? Or undermining a pygame game? - pythonDefensive Copy: Should I List in Javadoc? - javahow to get an updated row (not counting) for updating a table - sqlSOAPpy Installation Error - soappyhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1717498/logging-read-access-to-svn&usg=ALkJrhgo2c04dkWyc-Bv3NkND5jn5NmAwwGet a hover string from a wrapped Silverlight TextBox - silverlightCREATE TABLE AS SELECT kills MySQL - sqlZend Framework 1.9.x and Firebug - phpAll Articles