[concurrency-interest] Fwd: Should I avoid compareAndSet with value-based classes?

Gil Tene gil at azul.com
Fri Jul 7 15:21:33 EDT 2017

On Jul 7, 2017, at 12:07 PM, Justin Sampson <jsampson at guidewire.com<mailto:jsampson at guidewire.com>> wrote:

Gil Tene wrote:

public void setInstant(final Instant newInstant) {

This is broken because there's no volatile write. It needs to be instantHolder.set(new BoxedInstant(newInstant)), and then BoxedInstant can be immutable. I don't think you can get away from instantiating a new box each time, if your interpretation is correct.

You are right that the code above is broken due to a missing volatile write. But I don't think we need to force allocation each time here. Instead, we can keep the box mutable and introduce the missing volatile write this way:

public void setInstant(final Instant newInstant) {
    BoxedInstant boxedInstant = instantHolder.get();
    instantHolder.set(boxedInstant); // to force volatile write

I believe that the various races possible between this  and other modifiers (other setInstant() caller, add() callers), are all possible in any case.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20170707/5e79e1ea/attachment.html>

More information about the Concurrency-interest mailing list