i'm reading volatile keyword in java , understand theory part of it.
but, i'm searching is, case example, shows happen if variable wasn't volatile , if were.
below code snippet doesn't work expected ( from aioobe)
class test extends thread { boolean keeprunning = true; public void run() { while (keeprunning) { } system.out.println("thread terminated."); } public static void main(string[] args) throws interruptedexception { test t = new test(); t.start(); thread.sleep(1000); t.keeprunning = false; system.out.println("keeprunning set false."); } } ideally, if keeprunning wasn't volatile, thread should keep on running indefinetely. but, stop after few seconds.
i've got 2 basic question :-
- can explain volatile example ? not theory jls.
- is volatile substitute synchronization ? achieve atomicity ?
volatile --> guarantees visibility , not atomicity
synchronization (locking) --> guarantees visibility , atomicity (if done properly)
volatile not substitute synchronization
use volatile when updating reference , not performing other operations on it.
example:
volatile int = 0; public void incrementi(){ i++; } will not thread safe without use of synchronization or atomicinteger incrementing compound operation.
why program not run indefinitely?
well depends on various circumstances. in cases jvm smart enough flush contents.
correct use of volatile discusses various possible uses of volatile. using volatile correctly tricky, "when in doubt, leave out", use synchronized block instead.
also:
synchronized block can used in place of volatile inverse not true.
Comments
Post a Comment