[concurrency-interest] Joda-Time immutability

Zhong Yu zhong.j.yu at gmail.com
Wed Aug 3 15:01:35 EDT 2011

On Wed, Aug 3, 2011 at 12:18 PM, Stephen Colebourne
<scolebourne at joda.org> wrote:
> On 3 August 2011 09:42, Zhong Yu <zhong.j.yu at gmail.com> wrote:
>> The fix with `volatile` is incorrect. Another thread may observe an
>> uninitialized field - writing the volatile field and publishing `this`
>> reference can be reordered. Only a `final` field can prevent that.
> Would that not require the constructor to expose the reference to 'this'?

static public DateTime globalVar;

// thread 1
globalVar = DateTime.now();

// thread 2
DateTime var = globalVar;
    var.getMillis(); // may return 0

Thread 2 may observe that globalVar is assigned before its iMillis
field is assigned. This will not happen if the field is final.

> Such a design might work, but would change the serialization of the
> mutable class.

I think it's backward compatible. It would be a problem if the
serializer uses the new class, and deserializer uses the old class. Is
that a use case you must code against?

- Zhong Yu

More information about the Concurrency-interest mailing list