Constructors and instruction reordering

The article you cited is conceptually correct. It’s somewhat imprecise in its terminology and usage, as is your question, and this leads to potential miscommunication and misunderstandings. It may seem like I’m harping on terminology here, but the Java Memory Model is very subtle, and if the terminology isn’t precise, then one’s understanding will suffer. … Read more

Threadsafe Vector class for C++

This is difficult because of algorithms. Suppose you wrapped vector so that all its member functions are serialised using a mutex, like Java synchronized methods. Then concurrent calls to std::remove on that vector still wouldn’t be safe, because they rely on looking at the vector and changing it based on what they see. So your … Read more

Not thread-safe Object publishing

The reason why this is possible is that Java has a weak memory model. It does not guarantee ordering of read and writes. This particular problem can be reproduced with the following two code snippets representing two threads. Thread 1: someStaticVariable = new Holder(42); Thread 2: someStaticVariable.assertSanity(); // can throw On the surface it seems … Read more

Pattern for lazy thread-safe singleton instantiation in java

the lazy thread-safe singleton instantion is kinda not easy to understand to every coder No, it’s actually very, very easy: public class Singleton{ private final static Singleton instance = new Singleton(); private Singleton(){ … } public static Singleton getInstance(){ return instance; } } Better yet, make it an enum: public enum Singleton{ INSTANCE; private Singleton(){ … Read more

executing block of code atomically

The answer depends on your definition of “atomic” I know of three valid definitions for atomic: Atomic as in synchronized: only one thread can be executing the code at one time; Atomic as in ACID: all of the action/block happens, or none of it does; Atomic as in uninterruptible: once the block starts, it can’t … Read more

Is there anyway to write the following as a C++ macro?

#define my_macro my_stream() class my_stream: public std::ostringstream { public: my_stream() {} ~my_stream() { ThreadSafeLogging(this->str()); } }; int main() { my_macro << 1 << “hello world” << std::endl; } A temporary of type my_stream is created, which is a subclass of ostringstream. All operations to that temporary work as they would on an ostringstream. When the … Read more

Is int? thread safe?

The question is poorly worded, and hence the confusion in the answers so far. The question should be “are reads and writes to a variable of type int? guaranteed to be atomic?” No, absolutely not. The spec is extremely clear on this point: Reads and writes of the following data types are atomic: bool, char, … Read more