Consider the following program: Here the stopRequested is not declared as volatile – so ideally the thread backgroupdThread must not stop – and execute endlessly But when running this locally – the thread backgroundThread is gracefully shutting down with the message: “Stopping the thread!!”. Are all the updates by the main() thread to the shared variable stopRequested visible to the
Tag: volatile
What is a usecase for Java AtomicReference#getAndSet?
What is a usecase for Java AtomicReference#getAndSet? In other words, is it correct assumption, that if the only method from AtomicReference that I use in my code is AtomicReference#getAndSet, then I …
java – synchronization and volatile variable
I’ve read from this article that: …Synchronized blocks also guarantee that all variables accessed inside the synchronized block will be read in from main memory, and when the thread exits the …
Is it necessary to make `AtomicBoolean` also `volatile`?
My understanding: Declaring a variable volatile guarantees the visibility for other threads about writes to that variable. Essentially, every write to volatile variable happens-before subsequent reads….
Using volatile for skipping method execution
I’ve never used volatile very often. Is it possible to use it to skip method execution if another thread executing it? I think in the code below it’s still possible that multiple threads pass the …
Does a synchronized block trigger a full memory fence for arrays?
I am confused about sharing arrays safely between threads in Java, specifically memory fences and the keyword synchronized. This Q&A is helpful, but does not answer all of my questions: Java arrays: synchronized + Atomic*, or synchronized suffices? What follows is sample code to demonstrate the issue. Assume there is a pool of worker threads that populates the SharedTable via
Volatile variable explanation in Java docs
when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change This is mentioned at http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html Can someone please provide an example of this? This first gave me an impression that the thread that reads a volatile variable will synchronize with
why using volatile with synchronized block?
I saw some examples in java where they do synchronization on a block of code to change some variable while that variable was declared volatile originally .. I saw that in an example of singleton class …
volatile with release/acquire semantics
Since Java 5, the volatile keyword has release/acquire semantics to make side-effects visible to other threads (including assignments to non-volatile variables!). Take these two variables, for example: Note that i is a regular, non-volatile variable. Imagine thread 1 executing the following statements: At some later point in time, thread 2 executes the following statements: According to the Java memory model,