[concurrency-interest] Immutable object conundrums

Peter Veentjer alarmnummer at gmail.com
Tue Jun 30 08:25:38 EDT 2009


> It seems to me that immutability for the sake of propagating constructor
> changes to main memory
> is something of a misnomer - this is more about using the 'final' keyword as
> a coarse grained hook into the
> java memory model. Maybe if we had more direct access to that memory model
> then we could ensure
> that mutable objects could safely be constructed as well, for example:
>
> public class MyMutableClass {
>   private String myNonFinal;
>
>   public MyClass() {
>      this.myNonFinal = "hello world";
>      MemoryModel.flush(); // flush-commit similar to other cache
> technologies
>   }
> }

I don't see a happens before relation between the write of the
myNonFinal example and the usage. So I don't think this example is
going to work.

> So my suggestion is that sometimes we rely on the side effects of 'final' to
> help with safe publication rather
> than expressing a desire to express immutable semantics. The only way I can
> see to gain the best of both
> worlds is to use java atomics, which I can declare final but whose contents
> I can modify.
>

If you use a handover (so from thread1 to thread2, without the object
being touched by the thread1 after handover) you need some kind of
mechanism to safely handover the reference (for example a volatile or
Atomic class). But actions also ensures that all writes done  in
thread1 prior to the handover, are visible after the handover in
thread1. In JCiP this is called 'piggybacking on synchronisation'.

so

class Person{String name;}

volatile Person global;

//thread1
void foo(){
   Person p = new Person();
   p.name ="peter";
   global = p;
}

//thread2
void bar(){
  Person p = global;
  if(p!=null){print(p.name);}
}

So you don't need to litter your code with all kinds of JMM cruft.



More information about the Concurrency-interest mailing list