Non-atomicity field questions
Brian Goetz
brian.goetz at oracle.com
Wed May 24 18:48:19 UTC 2023
On 5/24/2023 1:52 PM, - wrote:
> Hello, quick question:
> If there's a nullable reference field in a null-restricted non-atomic
> value class, is this possible:
We don't null-restrict classes, we null-restrict variables. So I think
the above pencils out to:
__non-atomic value class X {
public String? s;
public implicit X();
public X(String! s) { this.s = s; }
}
X! x;
right?
> 1. Declare a reference field, like a String, without heap pollution
> concerns;
> 2. Limit the values of fields (of course, permit zero-default values)
> for all instances of this class, such as nonnegative long field, null
> or String reference containing no tabs, etc.
If I understand your question, you want to impose representational
invariants, with the proviso that the zero-default representation is
always valid. To do so, you can declare an implicit constructor (which
produces the zero-default value) and an explicit constructor which does
the plain vanilla argument validation / mapping to representation that
constructors always do.
> This requires constructors to be executed for non-default instance
> creation, but individual field validation is independent, and valid
> object state is still the cartesian product of valid individual field
> states.
The role of a constructor is to establish an object's state consistent
with its invariants. But some invariants are per-field, and some are
cross-field:
class NonNegativeInt {
// per-field invariants
NonNegativeInt(int i) {
if (i < 0) throw ...
this.i = i;
}
}
class Range {
// cross-field invariant
Range(int lo, int hi) {
if (lo > hi) throw ...
...
}
}
The choice to accept non-atomicity should include "no cross-field
invariants", since a non-atomic value could tear under race. Plenty of
classes, though, are more like NonNegativeInt than Range.
Does this answer your question?
More information about the valhalla-dev
mailing list