#1254 Race condition involving const is possible

vkuzkokov Thu 14 Oct 2010

Let's begin with a sample source

using concurrent
class Main {
  static Void main()
  {
    Actor a := Actor(ActorPool()) |Crazy x| {
      echo(x.z)
      Actor.sleep(100ms)
      echo(x.z)
    }
    Crazy u := Crazy(a)
    a.send(null)
  }
}
const class Crazy {
  const Int z
  new make(Actor a) {
    a.send(this)
    Actor.sleep(100ms)
    z = 12
  }
}

Output:

12
0

I just shared mutable state. Nuff said.

Possible solution: isImmutable to be set true only at the end of construction.

rfeldman Fri 15 Oct 2010

That rule makes good sense in general. Technically speaking, the object is not immutable during construction because its fields can change state from undefined to defined, which this example illustrates perfectly.

And since they are not yet immutable, it only makes sense that isImmutable would return false during construction.

(Which would lead to a compiler error for the above code, one hopes - certainly that would be the desired behavior.)

brian Tue 19 Oct 2010

While it might be nice to handle things like isImmutable correctly in a constructor, that wouldn't actually be pragmatic. It would require an extra field on each instance to store its state. Constructors are always ugly affairs (in both Java and Fantom) because things aren't just baked yet for initialization. But you can't really stop references from escaping without severe limits. So I think you just have to be careful in your constructors to not let references escape until the object is fully constructed.

qualidafial Tue 19 Oct 2010

This is why I've suggested in the past using a thread-local stack of objects in construction. This would introduce roughly the same performance overhead but the resource overhead would be just a single list for the entire thread.

brian Wed 20 Oct 2010

This is why I've suggested in the past using a thread-local stack of objects in construction. This would introduce roughly the same performance overhead but the resource overhead would be just a single list for the entire thread.

Not sure I follow that. How could you do anything as efficiently as it works now (which is basically as fast a Java object creation with maybe an extra method call).

qualidafial Wed 20 Oct 2010

Not sure I follow that. How could you do anything as efficiently as it works now (which is basically as fast a Java object creation with maybe an extra method call).

I was only addressing the memory overhead. Using a single List per thread to keep track of objects in construction would be a negligible overhead compared to adding a Bool to every single const instance.

In terms of CPU cycles, either of these options would carry a performance cost.

Login or Signup to reply.