java - Why could this code fail? -


while reviewing this question noticed code:

class mythread extends thread {   private boolean stop = false;    public void run() {     while(!stop) {       dosomework();     }   }    public void setstop() {     this.stop = true;   } } 

however don't understand why fail. other threads not access "actual" stop variable?

the instance variable stop needs volatile, otherwise there's no guarantee other threads see changes it. there lot of conflicting interests @ work: threads want consistent view of program state, cpus want able cache data, jvm wants able reorder instructions. making instance variable volatile means can't cached , happens-before relationships established limit instruction reordering.

see this other answer (+1) example of reordering may happen without marking variable volatile.

(by way using interruption thread cancellation preferable using instance variable.)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -