เนื่องจากการทำงานแบบ thread แต่ละ thread จะมี memory ของตัวเองซึ่งอาจจะไม่สามารถเห็นระหว่างกันได้ และเราไม่สามารถกำหนดลำดับการทำงานได้ เราไม่มั่นใจได้ว่า thread แรกจะทำงานไปถึงขั้นตอนไหนแล้ว ขณะที่ thread ที่สองถึงขั้นตอนนี้
The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

จากรูปถ้าเรากำหนด ready เป็น volatile เมื่อ thread2 มาอ่านตัวแปร ready, thread2 จะอ่าน memory ที่ thread1 มีก่อนที่จะสั่ง ready = true มาด้วย จึงมั่นใจได้ว่า thread2 จะ print 42
แต่ถ้าไม่เป็น volatile ตอนที่ thread2 มาอ่านตัวแปร ready แล้วได้ true ไป แต่ตัวแปร answer ไม่ได้ไปด้วยก็จะ print ออกมาผิด
tip! ถ้า ready เป็น volatile นอกจาก thread2 จะ update memory ของ thread1 ก่อนสั่ง ready = true แล้ว ยังจะ update memory ของทุกๆ thread ที่มีการ set ค่าให้ ready อีกด้วย
ที่มา - http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html
0 ความคิดเห็น:
แสดงความคิดเห็น