[concurrency-interest] Should I avoid compareAndSet with value-based classes?
oleksandr.otenko at gmail.com
Fri Jul 7 13:41:49 EDT 2017
I think there is a bit of a split mind here: what the value class instance is (is it Object-like in the language spec, so does it behave like references?), and what the value class instance is implemented as by the JVM (is it Object-like in the actual memory layout, so does it behave like a reference?).
The value class instance does not necessarily fit in a single machine word - time Instance certainly doesn’t. If the time Instance is “inlined” by the JVM, then you can’t guarantee atomicity of writes, and atomicity of reads also, so the reads also need to use a synchronized block - whether demand that explicitly from the programmer, or do that implicitly, like it’s done for volatile long on some platforms, does not matter. (Or use StampedLock, as Doug points out).
If it’s done implicitly by the JVM that “inlines” the value class instance, then there is no need to require extra steps from the programmer.
> On 7 Jul 2017, at 14:26, Andrew Haley <aph at redhat.com> wrote:
> On 07/07/17 13:27, Alex Otenko wrote:
>> If you are updating a reference, then CAS can also work.
> Well, that is the subject of some contention here, because the spec
> *explicitly* says you should not compare quality, and that is what a
> CAS does. But the re is no need for a CAS; synchronized will do, and
> it allows you to call equals() rather than using reference equality.
> In practice, avoiding the use of reference equality is not a problem.
> That is my point.
>> If you are talking about imitating update of the reference by
>> mutating inlined object contents,
> You're not in this case.
>> then you do need synchronized for readers.
> Andrew Haley
> Java Platform Lead Engineer
> Red Hat UK Ltd. <https://www.redhat.com>
> EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671
More information about the Concurrency-interest