Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Volatile - synchronized ?

 
kri shan
Ranch Hand
Posts: 1473
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can i specify volatile variable within synchronized method or synchronized block ? Volatile works only with multithreaded code(non thread-safe) ?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
volatile is a modifier that only applies for instance and class variables.

It makes that different Threads do not cache the value of the corresponding variable and hence always retrieve the latest, up-to-date, could-have-been-modified-by-another-thread value.
 
Monu Tripathi
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are interested in understanding Synchronization and about volatile modifier and if you have time, consider reading Synchronization and Java Memory Model.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably best moved to the threads forum.
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One thing to note, there is only one non access modifier for local variables and that is final. There are no other non access modifiers for local variables.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic