java - coding a proof for potential concurrency issue -
i'm reading "java concurrency in practice" , trying write piece of code show class presented example in chapter 3.5.1 can indeed introduce problems.
public class holder { public int n; public holder(int n) { this.n = n; } public void assertsanity() { if (n != n) { throw new assertionerror("sanity check failed!!"); } } } it's said there if used in following way(i believe it's fact field public, concurrency problem may happen.
public holder holder; public void initialize() { holder = new holder(42); } so i've come code see if bad happens.
public class sanitycheck { public holder holder; public static void main(string[] args) { sanitycheck sanitycheck = new sanitycheck(); sanitycheck.runtest(); } public void runtest() { (int = 0; < 100; i++) { new thread() { @override public void run() { while (true) { if (holder != null) { holder.assertsanity(); } try { thread.sleep(1); } catch (interruptedexception e) { } } } }.start(); } try { thread.sleep(1000); } catch (interruptedexception e) { } initialize(); } public void initialize() { holder = new holder(42); } } but nothing bad happens, no assertionerror has been thrown.
could please me figure out why code doesn't brake anything?
thank in advance time.
the fact code not thread safe , could create concurrency issues not mean will so.
the java memory model (jmm) says how program must behave when synchronized. not how program could behave when not.
for example, jvm enforce sequential consistency compliant jmm , no concurrency issue ever happen.
w.r.t. specific example, unlikely break on x86/hostpot combination.
Comments
Post a Comment