Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Section A.5. The Volatile Keyword

A.5. The Volatile Keyword

As we mentioned in Chapter 3, the act of setting the value of a variable (except for a long or a double) is atomic. That means there is generally no need to synchronize access simply to set or read the value of a variable.

However, Java's memory model is more complex than that statement indicates. Threads are allowed to hold the values of variables in local memory (e.g. in a machine register). In that case, when one thread changes the value of a variable, another thread may not see the changed value. This is particularly true in loops that are controlled by a variable (like the shouldRun variable that we use to terminate threads): the looping thread may have already loaded the value of the variable into a register and will not necessarily notice when another thread sets that variable to false.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint