• Post Reply Bookmark Topic Watch Topic
  • New Topic

Volatile fields and postincrement  RSS feed

 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote: . . .


Run this program, and you will see an eleven appear from time to time.

Henry
I did, only I had the volatile field initialised to 0, so I saw lots of 1s and lots of 0s.

Is that because the field is marked volatile? Does the value of x get written back to RAM after the x++ is executed? Then the value read from the print call is taken from RAM?
Would that not happen were the field not marked volatile? Would that be because the new value is held in cache or register to be reassigned to x immediately?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. Volatile variables are not cached with registers, and hence, changes by one thread are seen by other threads.

In this example, if it isn't declared as volatile, it may still work, but since changes don't always take effect (seen between threads), it may not be easily seen.

Henry
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is what I thought. Thank you
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!