Let non-threadsafe, mutable object X be constructed in thread A. A passes X, post construction, to thread B. B mutates X and A never accesses X again.
Will the state of X always be properly visible to B?
Is X effectively thread confined?
My reading of Java Concurrency in Practice seems to indicate that X is not properly published but I cannot cause any problems for thread B in test rigs that run millions of replications. I suspect this is just dumb luck.
For background, X represents a multitude of complex classes over which I have no control that are authored by modelers who have only a basic knowledge of Java. It is strongly preferred that X has no synchronized blocks or other concurrency mechanisms or requirements.
I am currently solving this problem by having thread A pass a thread-safe factory for X that B invokes, thus making X thread confined.
Publication only safe for final fields
The Java Memory Model doesn't guarantee that the object X will be completely published (fully constructed) to thread A.
To ensure that, you would need to make it immutable (all member fields final) or synchronize.
Quoting JSR-133:
The semantics of final fields have been strengthened to allow for thread-safe immutatability
without explicit synchronization. This may require steps such as store-store barriers at the
end of constructors in which final fields are set.
Only thing you need to avoid is leaking fields out of the class before the constructor finishes.
Testing
jcstress has in fact a sample project to demonstrate consequences of racing during publication: JMMSample_06_Finals.java
Note that some efforts had to be done to replicate the problem, like using many fields.
The implementation of the JMM depends naturally on the particular JRE that you are using and also the effects of memory barriers being used depend on the hardware being used.
On my hardware using Oracle JDK 8 I'm not able to reproduce unsafe publication using the sample with jcstress.
Synchronizing
There is a "happens-before" relationship between all synchronization actions. This is known as the synchronization order. Basically when you use any synchronization mechanism, you have the guarantee that actions before it will be visible after it.
As concluded in the Java Language Specification:
If a program is correctly synchronized, then all executions of the program will appear to be sequentially consistent
In practice
In practice it's very hard to run into problems due to actions taken in a constructor not being visible by threads using the object.
A primary reason is the usage of synchronization mechanisms. You can check some of the actions that will ensure the happens-before relationship in the javadoc: Memory Visibility
Also as I mentioned with the jcstress sample, JRE nowadays seems to be very good in ensuring consistent results even when it doesn't need to according to the language specification.
Related
The memory model is defined in 17.4. Memory Model.
The final field multi-threading guarantees are given in 17.5. final Field Semantics.
I don't understand why these are separate sections.
AFAIK both final and the memory model provide some guarantees.
And any real program execution must respect both guarantees.
But it's now clear whether the final guarantees work for the intermediate executions used to validate causality requirements in 17.4.8. Executions and Causality Requirements.
Another unclear moment is that 17.5.1. Semantics of final Fields defines a new "special" happens-before, which differs from the happens-before in the memory model:
This happens-before ordering does not transitively close with other happens-before orderings.
If these are the same happens-before, then the happens-before isn't a partial order anymore (because it isn't transitive).
I don't understand how this doesn't break things.
If these are different happens-before, then it's not clear what the one in 17.5. final Field Semantics does.
The happens-before in 17.4. Memory Model is used to restrict what a read can return:
Informally, a read r is allowed to see the result of a write w if there is no happens-before ordering to prevent that read.
But 17.5. final Field Semantics is a different section.
The special 'final field guarantees' part was a later add-on. Documentation sometimes follows the quirks of history - possibly, had the 'final field guarantee' issue been discovered prior to the first release of the JMM, the documentation would have been structured differently.
In other words, you're asking for 'why is this stuff in a separate chapter' and perhaps the answer is: "Because it was added in a later version of java, and therefore it was written at a completely different time; a new chapter is presumably the simplest way to add some more documentation". We're talking about decades ago at this point, of course.
§17.5 explains its purpose. Quote:
The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.
In other words, in the distant past, you could do this:
Thread A:
Make a new object. The constructor is 'well behaved' 1
Communicate the ref to this new object to another thread. Possibly in an unsafe way.
Thread B:
The receiving thread gets the correct ref (either because you did it safely with synchronization, i.e. happens-before relationship set up properly, or because you did it unsafely, but the JMM does not guarantee that unsafe code fails to work: It may still work).
It calls a method of this object.
Said object witnesses a final-marked field that isn't initialized, because the initialization did occur in thread A, but no happens-before relationship exists, and re-ordering and other shenanigans means that this thread doesn't see it yet.
This is extremely annoying. Part of the point of immutable classes is that you can more or less print out the JMM and set it on fire. You just don't need to care about virtually every tricky rule in it if your system is an amalgamation of immutable types. Except, it didn't actually work out that way prior to the existence of §17.5
The JMM as a general principle is designed to give any JVM implementations as few 'handcuffs' as possible whilst making developing for the JVM as uncomplicated as possible. It's a fine line - for example, had the JMM simply stated: "The JVM is free to re-order whatever it wants at any time, and cache whatever it wants, at any time, for whatever duration it wants", then writing JVMs that run code quickly and according to spec would be 'easier' (JVM impls would be faster), but, writing multithreaded code that actually does what you intended it to becomes borderline impossible. On the flipside, the JMM could also have guaranteed that re-ordering in the JVM is impossible to observe regardless of circumstance or architecture. But then JVMs would be slow as molasses, see Python and its much maligned global interpreter lock.
The JMM tries to be the happy compromise. And §17.5 is written with the same spirit.
It basically says:
You CAN rely on the notion that any well-behaved construction means that final fields will just work out without having to worry about happens-before relationships whatsoever.
However, you CANNOT, at all, rely on HOW the JVM implements the guarantee. In particular, we have defined what you can exactly rely on in terms of Happens-Before, but it's not the same H-B that the rest of the JMM talks about. We guarantee you that well-behaved construction means final fields won't be an issue but that's as far as our guarantee goes: You cannot use this guarantee to then force other guarantees out of the JMM; you can't use this mechanism as a wonky way to establish H-B for other stuff, for example.
The JMM buys room to maneuver for JVM impls. Whether a JVM impl actually uses it, is up to the JVM implementor. In other words, a JVM implementor may well decide to implement §17.5 by using the same locking mechanisms it uses to guarantee the H-B stuff in §17.4, and thus effectively you can apply properties like 'H-B relationships are transitive'. The point of the JMM is partly to allow JVM impls to take some pretty drastically different approaches to how the guarantees it dictates are in fact guaranteed. That's because JVMs have to be written so that they can run code about as fast as native code could on a wide variety of hardware, whilst still being a target platform that isn't impossible to develop for.
Quite the tightrope walk. This is the primary underlying explanation for the JMM can be obtuse and bizarre at times.
[1] A 'well behaved' constructor:
Does not pass its own reference (this) to any code outside of its own class during construction.
Does not invoke any of its own instance methods that then read its own fields (or, especially problematic, which can be overridden by subclasses, whose implementation uses its own fields). Basically: Calling any non-final method is an instant "You are not well behaved" violation.
Does not send any object refs of things I wishes to store in fields to code in other classes during construction. Even if it has already assigned it to the final field before doing so.
Are AtomicIntegers considered synchronization primitives, or is it just the methods provided by Java (wait(), notify(), etc).
I am confused about the definition of primitives, as atomicintegers can operate on int and provide lock free thread sage programming. Without the use of synchronized.
AtomicInteger is a class. Its methods are... well, methods. Neither one of those would be considered a synchronization primative.
The compareAndSet method, which is also used by incrementAndGet and other such methods, uses Unsafe.compareAndSwapInt (on OpenJDK 7, which is what I have handy). That's a native method — so it could well be considered a primitive. And in fact, on modern CPUs, it translates to a CAS instruction, so it's a primitive all the way down to the hardware level.
The class also relies on volatile's memory visibility, which is also a synchronization primitive.
I think this question is a bit "vague"; but I think that "language primitive" typically refers to language elements that are part of the core of the language.
In other words: the keywords, and the associated semantics. In that sense; I would see the synchronized (in its two meanings) and volatile keywords as being the only "primitive" regarding multithreading.
Of course, classes such as Object; and therefore all its methods like wait(), notify() ... are also an essential part of Java (one which you can't avoid in the first place). And of course, same can be said about the Thread class.
Long story short: you can differentiate between concepts that exist as language keywords (and are thus handled by the compiler); and "on-top" concepts that come as "normal" classes. And as the answer from yshavit nicely describes, certain aspects of AtomicInteger can be directly mapped into the "native" side of things. So the real answer is maybe that, as said, the term "primitive" doesn't provide much aid in describing/differentiating concepts regarding Java multi-threading topics.
Regarding your first query:
Are AtomicIntegers considered synchronization primitives, or is it just the methods provided by Java (wait(), notify(), etc).
No. AtomicInteger is neither a method nor synchronized primitive.
AtomicInteger is a class with methods. Have a look at oracle documentation page on atomic packages
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
The classes in this package also contain methods to get and unconditionally set values, as well as a weaker conditional atomic update operation weakCompareAndSet
Regarding your second query:
I am confused about the definition of primitives, as atomicintegers can operate on int and provide lock free thread sage programming. Without the use of synchronized.
One key note:
The scope of synchronized is broad in nature compared to AtomicInteger or AtomicXXX variables. With synchronized methods or blocks, you can protect critical section of code, whcih contains many statements.
The compareAndSet method is not a general replacement for locking. It applies only when critical updates for an object are confined to a single variable.
Atomic classes are not general purpose replacements for java.lang.Integer and related classes. However, AtomicInteger extends Number to allow uniform access by tools and utilities that deal with numerically-based classes.
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.
I came across this line "some functions are inherently thread-safe, for example memcpy()"
Wikipedia defines "thread-safe" as:
A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.
OK. But what does inherently mean? Is it related to inheritance?
It is not related to inheritance. It is an informal expression and means more like
"some functions are thread-safe by their nature". For example a function which does not
touch any shared values/state is thread safe anyway i.e. "is inherently thread-safe".
In this context I interpret it as "without having been designed to achieve it, it still is thread-safe".
There is no direct link to the concept of inheritance, although of course the words are related. This is not an example of inheritance in the object-oriented programming sense, of course. This is just a function, that from its core nature gets the property of being thread-safe.
Of course there's nothing magic about memcpy() being inherently thread-safe, either. Any function without internal state or "shared" side-effects will be so, which is why functional programming, where all functions are supposed to be "pure" and lack side-effects, lends itself so well to parallel programming.
In practice it's hard on typical computers to get "real work" done without side-effects, particularly I/O is very much defined by its side-effects. So even pure functional languages often have some non-functional corners.
Update: Of course, memcpy() is not free from side-effects, it's core purpose is to manipulate memory which, if shared between threads, certainly isn't safe. The assumption has to be that as long as the destination areas are distinct, it doesn't matter if one or more threads run memcpy() in parallel.
Contrast this with e.g. printf(), which generates characters on a single (for the process) output stream. It has to be explicitly implemented (as required by POSIX) to be thread-safe, whereas memcpy() does not.
An inherently thread safe function, is safe without having to take any specific design decisions regarding threading, it is thread safe simply by virtue of the task it performs as opposed to being redesigned to force thread safety. Say I write the very simple function:
int cube(int x)
{
return x*x*x;
}
It is inherently thread safe, as it has no way of reading from or writing to shared memory. However I could also make a function which is not thread safe but make it thread safe through specific design and synchronization. Say I have this similar function to before:
void cubeshare()
{
static int x;
x = x * x * x;
printf("%l", x);
}
This is not thread safe, it is entirely possible it could have the value of x change between each use (well this is actually unlikely in reality as x would get cached but lets say we are not doing any optimization).
We however could make this thread safe like this (this is pseudo code, a real mutex is more complicated):
void cubesharesafe(mutex foo)
{
static int x;
lockmutex(foo);
x = x * x * x;
printf("%l", x);
unlockmutex(foo);
}
This is however not inherently thread safe, we are forcing it to be through redesign. Real examples will often be far more complicated than this but I hope that this gives an idea taken to the most simple possible level. If you have any questions please comment bellow.
In case of memcpy, only a single thread is able to provide writes from a specific source to a specific destination. : thread-safe by initial design so.
Inherently means: without needing to "tune" the base function to achieve the goal, in this case: thread safety.
If multiple threads could interfere the same "channel" at the same time, you would end up with problem of thread-safety related to shared chucks of data.
inherent means Existing in something as a permanent.
it has nothing to do with inheritance..
by default,or already some methods are thread safe...in order to protect or avoid multitasking problems..
vector,hash table..are some of the example classes that are inherently thread safe..
nothing..confusing..there are some functions..which is thread safe by default..
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).