• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Volatile fields and postincrement

 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is what I thought. Thank you
 
reply
    Bookmark Topic Watch Topic
  • New Topic