It would be beneficial if there was a way to create StableFieldUpdater constructs that can be used to safely manipulate stable instance fields. Only one updater is needed per class, similar to `AtomicIntegerFieldUpdater`.
Here is an example of how such a construct could be used:
public final class LazyFoo {
private final Bar bar;
private final Baz baz;
private static final ToIntFunction<LazyFoo> HASH_UPDATER =
StableFieldUpdater.ofInt(LazyFoo.class, "hash",
l -> Objects.hash(l.bar, l.baz), -1);
@Stable
private int hash;
public LazyFoo(Bar bar, Baz baz) {
this.bar = bar;
this.baz = baz;
}
@Override
public boolean equals(Object o) {
return o instanceof Foo that &&
Objects.equals(this.bar, that.bar) &&
Objects.equals(this.baz, that.baz);
}
@Override
public int hashCode() {
return HASH_UPDATER.applyAsInt(this);
}
}
Here is an example of how such a construct could be used:
public final class LazyFoo {
private final Bar bar;
private final Baz baz;
private static final ToIntFunction<LazyFoo> HASH_UPDATER =
StableFieldUpdater.ofInt(LazyFoo.class, "hash",
l -> Objects.hash(l.bar, l.baz), -1);
@Stable
private int hash;
public LazyFoo(Bar bar, Baz baz) {
this.bar = bar;
this.baz = baz;
}
@Override
public boolean equals(Object o) {
return o instanceof Foo that &&
Objects.equals(this.bar, that.bar) &&
Objects.equals(this.baz, that.baz);
}
@Override
public int hashCode() {
return HASH_UPDATER.applyAsInt(this);
}
}
- relates to
-
JDK-8355378 Annotate lazy hash fields @Stable
-
- Open
-
- links to
-
Review(master) openjdk/jdk/25040