Volatile variable reading and writing - java

If we have volatile variable, we are guaranteed that if we have two threads and the two threads read they will get the value from the main memory,also if we write and then a read happens we will get in the read the changes, but what are guaranteed and not guaranteed when we have many threads reading and writing on the volatile variable?

NO. volatile won't do that.
Volatile: Almost Useless for Multi-Threaded Programming
There is a widespread notion that the keyword volatile is good for
multi-threaded programming. I've seen interfaces with volatile
qualifiers justified as "it might be used for multi-threaded
programming". I thought was useful until the last few weeks, when it
finally dawned on me (or if you prefer, got through my thick head)
that volatile is almost useless for multi-threaded programming. I'll
explain here why you should scrub most of it from your multi-threaded
code.
...
There may be languages where it may have such an effect, but in C, the answer is an emphatic NO.
EDIT:
Now that the language is specified as Java, the answer is different, since Java implements its own memory model, and the volatile keyword does have a significant impact. See Do you ever use the volatile keyword in Java? and many other questions.

Related

volatile + synchronized combination in multithreaded scenario

I have good knowledge of synchronization internals and basic knowledge of volatile internals.
I have one query, which is follow-up to below SE question:
Why is volatile used in this example of double checked locking
I'm confused about one part. If I strictly follow above example, I have to add volatile to many variables but I am sure that all multi-threaded applications are not using this volatile + synchronized combination.
If synchronization is not guaranteeing memory consistency as per above example, what are the use cases of using combination of volatile variables with synchronization code?
When a variable is defined volatile it is read from the main memory instead of registries.
So each processor will see the same value.
In the double check the variable is defined as volatile to be sure to check outside of synchronized block will intercept most of cases.
If the variable is not volatile the code will work, but if you have more processors you can go inside of the synchronized block more than needed (also when the variable is not null).
If all access to a variable are done in the synchronized block a volatile is not necessary at all.
The combination of volatile and synchronized in that question/answer only applies to double-checked locking.
If you're not doing double-checked locking, and are accessing your shared variables always within the protection of the same synchronized monitor (which is how applications most commonly access shared variables, if they're not using the java.util.concurrent classes), then you don't need volatile.
In any case, this doesn't mean that double-checked locking is a good idea. Although the volatile + synchronized construct will make double-checked locking work, it doesn't offer any significant performance benefit, as you can also read in #alf's answer to the question you refer to.

Volatile Keyword is of no use When using synchronized?

I was trying to understand the use of volatile keyword in java. I understand it will write the data in main memory not in thread cache.
But is that really useful. I am using multi threading and
shouldn't I be using synchronized cause I don't want dirty reads to other threads. so at what exact situation volatile can be useful and most important to use?
Please give some example.
synchronized is much more expensive than plain volatile.
volatile is useful when you just need to read/write single variable and don't care about atomicity of complex structures.
synchronized is useful when you need to perform complex operations, update several variables or set one variable when compared another one and ensure the atomicity of such operation. Also it is used when doing higher level synchronization such as conditions, i.e. synchronized/wait/notify in java. But for that Lock/Condition can be used too.
For even better explanation about using volatile variables you can view the following link with JB Nizet's answer. It compliments well the answer posted by Zbynek and further explains the relation between volatile, atomic variables & complexity. Hope this helps.

Risks of volatile-mutable fields in single-threaded contexts?

Is it safe to use the :volatile-mutable qualifier with deftype in a single-threaded program? This is a follow up to this question, this one, and this one. (It's a Clojure question, but I added the "Java" tag because Java programmers are likely to have insights about it, too.)
I've found that I can get a significant performance boost in a program I'm working on by using :volatile-mutable fields in a deftype rather than atoms, but I'm worried because the docstring for deftype says:
Note well that mutable fields are extremely difficult to use
correctly, and are present only to facilitate the building of higher
level constructs, such as Clojure's reference types, in Clojure
itself. They are for experts only - if the semantics and implications
of :volatile-mutable or :unsynchronized-mutable are not immediately
apparent to you, you should not be using them.
In fact, the semantics and implications of :volatile-mutable are not immediately apparent to me.
However, chapter 6 of Clojure Programming, by Emerick, Carper, and Grand says:
"Volatile" here has the same meaning as the volatile field modifier in
Java: reads and writes are atomic and must be executed in
program order; i.e., they cannot be reordered by the JIT compiler or
by the CPU. Volatiles are thus unsurprising and thread-safe — but
uncoordinated and still entirely open to race conditions.
This seems to imply that as long as accesses to a single volatile-mutable deftype field all take place within a single thread, there is nothing to special to worry about. (Nothing special, in that I still have to be careful about how I handle state if I might be using lazy sequences.) So if nothing introduces parallelism into my Clojure program, there should be no special danger to using deftype with :volatile-mutable.
Is that correct? What dangers am I not understanding?
That's correct, it's safe. You just have to be sure that your context is really single-threaded. Sometimes it's not that easy to guarantee that.
There's no risk in terms of thread-safety or atomicity when using a volatile mutable (or just mutable) field in a single-threaded context, because there's only one thread so there's no chance of two threads writing a new value to the field at the same time, or one thread writing a new value based on outdated values.
As others have pointed out in the comments you might want to simply use an :unsynchronized-mutable field to avoid the cost introduced by volatile. That cost comes from the fact that every write must be committed to main memory instead of thread local memory. See this answer for more info about this.
At the same time, you gain nothing by using volatile in a single-threaded context because there's no chance of having one thread writing a new value that will not be "seen" by other thread reading the same field.
That's what a volatile is intended for, but it's irrelevant in a single-thread context.
Also note that clojure 1.7 introduced volatile! intended to provide a "volatile box for managing state" as a faster alternative to
atom, with a similar interface but without it's compare and swap semantics. The only difference when using it is that you call vswap! and vreset! instead of swap! and reset!. I would use that instead of
deftype with ^:volatile-mutable if I need a volatile.

What is the Java equivalent of `nonatomic` in Objective C?

My guess is that it would be similar with volatile keyword, which gives happened-before relation, visibility and atomic value assignment(in case of >32bit types as long) in Java. Is it?
(edit: my guess was that atomic attribute was similar to volatile, not nonatomic but turns out it wasn't anyway)
"Atomic" in Objective C, according to this article, is similar to a synchronized variable in Java, such that it cannot be changed by two threads at the same time. nonatomic is the opposite, meaning a variable that is not synchronized, and therefore could be changed by multiple threads simultaneously.
Regarding volatile, according to wikipedia:
The Java programming language also has the volatile keyword, but it is used for a somewhat different purpose. When applied to a field, the Java volatile guarantees that:
(In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it's generally not a useful threading construct.)
(In Java 5 or later) Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.
Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.

Is there any case where I should prefer 'volatile' over exclusive synchronization?

I know using volatile keyword in Java we get some kind of weak synchronization (It allows visibility updates but do not provide actual locking). Is there any situation where volatile should be given preference over actual locking in implementing concurrent programs. A somewhat similar question is there on SO which says volatile as a synchronization mechanism but that was tagged to C#.
If the shared state consists in a single field, and you don't use any get-and-set construct (like i++ for example) to assign it, then volatile is good enough. Most of the volatile usages can be replaced by the use of AtomicXxx types, though (which provide atomic get-and-set operations).
In short, you should prefer to avoid locks wherever they are not necessary since locks expose your program to deadlocks and deter performance by excluding concurrency from critical parts of code. So, whenever the situation permits, by all means rely on volatile; if all you additionally need is atomic two-step operations like compare-and-swap, use AtomicReference. Fall back to synchronized only for the scenarios where this is the only option. For example, if you need to lazily initialize a heavy object, you'll need locks to prevent double initialization—but again, not to fetch the already initialized instance (double-check idiom).
Volatile guarantees that all threads will see the last write of a variable by any other thread, that's it. There's no synchronization involved. If you synchronize both read and write method of an instance variable, then you don't have to make that variable volatile (all threads will see the most recent write).

Categories