Records and bi-directional relationships
Novi
novitools.novi at web.de
Sun Dec 15 13:14:37 UTC 2019
Hello Brian Goetz,
I always wonder what is the best way to model cycles in Java when using
immutable classes.
> What you're doing in the `Surface` constructor is allowing the `this`
> reference escape during construction, which undermines the memory model
> guarantees for final fields.
After reading your article "Safe construction techniques"[1], I thought it
we be okay if the `this` reference escapes during construction as long as
no other thread can see it.
> What you're doing in the `Surface` constructor is allowing the `this`
> reference escape during construction, which undermines the memory model
> guarantees for final fields.
Does an escaped `this` reference always undermine the memory model
guarantees for final fields?
Or does it only undermine the memory model if the `this` reference is
published during construction so that it is accessible from other threads?
- Novi
1: https://www.ibm.com/developerworks/library/j-jtp0618/index.html
Am 14.12.2019, 23:11 Uhr, schrieb Brian Goetz <brian.goetz at oracle.com>:
> I think you are asking: is it possible to create cycles with records?
> And the answer is, mostly no. (You can have records that have mutable
> components and then later mutate them to be cyclic.
>
> What you're doing in the `Surface` constructor is allowing the `this`
> reference escape during construction, which undermines the memory model
> guarantees for final fields.
>
> On 12/14/2019 4:58 PM, Gunnar Morling wrote:
>> Hi all,
>>
>> I was exploring the records feature in the latest 14 EA build a bit. An
>> interesting question came up in how records will work for
>> bi-directional relationships between two record types.
>>
>> I found no way to instantiate such pair of records without creating a
>> temporary instance of one of the two (unlike with regular classes,
>> where I
>> could wire the relationship from within the constructor of one). Did I
>> miss
>> an alternative way to do so (see below for what I came up with)?
>>
>> A related question: this program will raise a StackOverflowError in the
>> toString() method. Is this an accepted limitation?
>>
>> Thanks,
>>
>> --Gunnar
>>
>> public class RecordsBidi {
>> public static void main (String... args) {
>> Surface surface = new Surface(new Point(1, 2));
>> System.out.println(surface);
>> }
>>
>> record Point(int x, int y, Surface owning) {
>> public Point(int x, int y) {
>> this(x, y, null);
>> }
>> }
>>
>> record Surface(Point center) {
>> public Surface(Point center) {
>> this.center = new Point(center.x, center.y, this);
>> }
>> }
>> }
More information about the amber-dev
mailing list