• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile variable in multithreading

 
priyanaka jaiswal
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


Volatile Variable is stored in main memory so that all thread can access the updated volatile variable.what is this main memory exactly in JVM ?How it stores volatile variable?
 
Sharmistha Sarkar
Ranch Hand
Posts: 50
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Volatile fields are instance or class (static) variables and are stored in the heap.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sharmistha Sarkar wrote:Volatile fields are instance or class (static) variables and are stored in the heap.


All member variables are stored on the heap. Nothing special about volatile there.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
priyanaka jaiswal wrote: Volatile Variable is stored in main memory so that all thread can access the updated volatile variable.what is this main memory exactly in JVM ?How it stores volatile variable?


The "main memory" that's referred to here is just the RAM in your computer. Each thread may have local copies of shared variables, such as in L1 or L2 cache, so a thread running on one CPU might be dealing with its local on-chip cache copy of a variable, while a thread running on a different CPU might have its own, separate copy of that variable in its on-chip cache.

By marking a variable volatile, we're saying that's not allowed to happen. All access to that variable must be against a single copy--no local caching.

 
drac yang
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
volatile has to do with the visibility issue which means other threads might possibly see an old value of a variable which has been operated by another thread, if it's modified by volatile, there would be no visibility issue on this variable in multithreaded environment.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic