concurrency - Volatile in java -
as far know volatile write happens-before volatile read, see freshest data in volatile variable. question concerns term happens-before , take place? wrote piece of code clarify question.
class test { volatile int a; public static void main(string ... args) { final test t = new test(); new thread(new runnable(){ @override public void run() { thread.sleep(3000); t.a = 10; } }).start(); new thread(new runnable(){ @override public void run() { system.out.println("value " + t.a); } }).start(); } } (try catch block omitted clarity)
in case see value 0 printed on console. without thread.sleep(3000); see value 10. case of happens-before relationship or prints 'value 10' because thread 1 starts bit earlier thread 2?
it great see example behaviour of code , without volatile variable differs in every program start, because result of code above depends only(at least in case) on order of threads , on thread sleeping.
you see value 0 because read executed before write. , see value 10 because write executed before read.
if want have test more unpredictable output, should have both of threads await countdownlatch, make them start concurrently:
final countdownlatch latch = new countdownlatch(1); new thread(new runnable(){ @override public void run() { try { latch.await(); t.a = 10; } catch (interruptedexception e) { // end thread } } }).start(); new thread(new runnable(){ @override public void run() { try { latch.await(); system.out.println("value " + t.a); } catch (interruptedexception e) { // end thread } } }).start(); thread.sleep(321); // go latch.countdown();
Comments
Post a Comment