If I'm right, someValue should be volatile, otherwise the 3rd step may not return the updated value (since A may have a cached value). Is it correct?
If thread B calls setSomeValue (), you need some kind of synchronization so that thread A can read this value. volatile
will not do this on its own, and synchronization of these methods will also fail. The code that does this, ultimately, regardless of the synchronization code you added, made sure that A: getSomeValue()
comes after B: setSomeValue()
. If you think you used a message queue to synchronize threads, this is because the memory changes made by thread A became visible to thread B as soon as thread B acquired a lock on the message queue.
If access to the class is carried out only in the second way, is there no need for unstable / synchronization, or is it?
If you really do your own synchronization, then it doesn't sound as if you care about whether these classes are thread safe. Make sure you are not accessing them from multiple threads at the same time; otherwise, any methods that are not atomic (specifying int) can lead to an unpredictable state. One common pattern is to put the general state in an immutable object so that you are sure that the receiving stream does not call any setters.
If you have a class that you want to update and read from multiple threads, I will probably do the easiest thing to get started, which often synchronizes all public methods. If you really think this is a bottleneck, you can explore some of the more complex locking mechanisms in Java.
So what is a flying guarantee?
For exact semantics, you may need to read tutorials, but one way to summarize them is that 1) any memory changes made by the last thread to access volatile will be visible to the current thread accessing the volatile, and 2) that access to volatile is atomic (it will not be a partially constructed object, or a partially designated double or long).
Synchronized blocks have similar properties: 1) any memory changes made by the last thread to access the lock will be visible to this thread, and 2) changes made inside the block are performed atomically with respect to other synchronized blocks
(1) means any changes in memory, not just changes in the volatile (we say JDK 1.5 post) or inside a synchronized block. This is what people mean when they refer to ordering, and this is done differently on different chip architectures, often using memory barriers.
In addition, in the case of synchronous blocks (2) only guarantees that you will not see inconsistent values ββif you are in another block synchronized with the same lock. It is generally recommended that you synchronize all access to shared variables if you really don't know what you are doing.