Skip to content

Conversation

@minborg
Copy link
Contributor

@minborg minborg commented Mar 10, 2025

Implement JEP 502.

The PR passes tier1-tier3 tests.


Progress

  • Change must be properly reviewed (1 review required, with at least 1 Reviewer)
  • Change must not contain extraneous whitespace
  • Commit message must refer to an issue
  • Change requires CSR request JDK-8342068 to be approved

Issues

  • JDK-8351565: Implement JEP 502: Stable Values (Preview) (Sub-task - P4)
  • JDK-8342068: Implement JEP 502: Stable Values (Preview) (CSR)

Reviewers

Contributors

  • Maurizio Cimadamore <mcimadamore@openjdk.org>

Reviewing

Using git

Checkout this PR locally:
$ git fetch https://git.openjdk.org/jdk.git pull/23972/head:pull/23972
$ git checkout pull/23972

Update a local copy of the PR:
$ git checkout pull/23972
$ git pull https://git.openjdk.org/jdk.git pull/23972/head

Using Skara CLI tools

Checkout this PR locally:
$ git pr checkout 23972

View PR using the GUI difftool:
$ git pr show -t 23972

Using diff file

Download this PR as a diff file:
https://git.openjdk.org/jdk/pull/23972.diff

Using Webrev

Link to Webrev Comment

@minborg
Copy link
Contributor Author

minborg commented Apr 24, 2025

/reviewers 1

@openjdk
Copy link

openjdk bot commented Apr 24, 2025

@minborg
The total number of required reviews for this PR (including the jcheck configuration and the last /reviewers command) is now set to 1 (with at least 1 Reviewer).

Copy link
Contributor

@viktorklang-ora viktorklang-ora left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@openjdk openjdk bot added ready Pull request is ready to be integrated csr Pull request needs approved CSR before integration and removed ready Pull request is ready to be integrated labels Apr 24, 2025
Comment on lines +387 to +389
* Invocations of {@link #setOrThrow(Object)} form a total order of zero or more
* exceptional invocations followed by zero (if the contents were already set) or one
* successful invocation. Since stable functions and stable collections are built on top

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can an exceptional invocation of setOrThrow be followed by a successful invocation?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setOrThrow might be invoked several times. If the first invocation failed because the supplier threw and then the second invocation (with the same supplier) succeded (because there was some state that changed), we have this situation.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

orElseSet is the method taking a supplier, setOrThrow doesn't.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh. I'm sorry for misreading this. The docs should say orElseSet rather than orElseThrow. Again, we will fix this in a follow-up PR.

public sealed interface StableValue<T>
permits StableValueImpl {

// Principal methods

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not important, not practical and hacky (exceptions as control flow), but technically all methods could be implemented in terms of orElseSet, so they could also be called "convenience methods":

trySet(c) {
    success = false
    orElseSet(() -> {success = true; return c})
    return succes
}

orElse(o) {
    try { return orElseSet(() -> throw) }
    catch { return o }
}

orElseThrow() {
    orElseSet(() -> throw)
}

isSet() {
    try { orElseSet(() -> throw) }
    catch { return false }
    return true
}

setOrThrow(c) {
    success = false
    orElseSet(() -> {success = true; return c})
    if (!success) throw
}

I guess these two comments (// Principal methods and // Convenience methods) could also just be omitted.

Comment on lines +56 to +57
// Used to indicate a holder value is `null` (see field `value` below)
// A wrapper method `nullSentinel()` is used for generic type conversion.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Used to indicate a holder value is `null` (see field `value` below)
// A wrapper method `nullSentinel()` is used for generic type conversion.
// Used to indicate a holder value is `null` (see field `contents` below)

The nullSentinel method no longer exists, the field is named contents.

* @param contents to set
* @throws IllegalStateException if the contents was already set
*/
void setOrThrow(T contents);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably also mention that IllegalStateException can be caused by recursive initialization (see trySet).

// Prevent reentry via an orElseSet(supplier)
preventReentry();
// Mutual exclusion is required here as `orElseSet` might also
// attempt to modify the `wrappedValue`

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// attempt to modify the `wrappedValue`
// attempt to modify `this.contents`

Comment on lines +1591 to +1592
return new NullableKeyValueHolder<>(k, inner.getValue().orElseSet(new Supplier<V>() {
@Override public V get() { return mapper.apply(k); }}));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This lazy Entry implementation should then also have a toString that doesn't evaluate the contents. It should also be used in forEachRemaining.

final StableValueImpl<E>[] delegates = ((StableList<E>)base).delegates;
final StableValueImpl<E>[] reversed = ArraysSupport.reverse(
Arrays.copyOf(delegates, delegates.length));
return StableUtil.renderElements(base, "Collection", reversed);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return StableUtil.renderElements(base, "Collection", reversed);
return StableUtil.renderElements(this, "StableList", reversed);

All other calls use "Stable...". Other view collections (ArrayList.SubList, ReverseOrderListView, AbstractMap.keySet, AbstractMap.values, HashMap.EntrySet) use the view reference (and not the underlying collection) for detecting self containment, so renderElements should use this instead of base for self.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason we are using "Collection" is that this method directly overrides AbstractCollection which is using "(this Collection)" for first-level circular references. I also think base should be replaced with this.

final Object value = e.getValue().wrappedContentAcquire();
final String valueString;
if (value == self) {
valueString = ("(this ") + selfName + ")";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
valueString = ("(this ") + selfName + ")";
valueString = "(this " + selfName + ")";

@Override
public String toString() {
if (root instanceof StableList<E> stableList) {
return StableUtil.renderElements(root, "StableList", stableList.delegates, offset, size);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return StableUtil.renderElements(root, "StableList", stableList.delegates, offset, size);
return StableUtil.renderElements(this, "StableList", stableList.delegates, offset, size);

Other view collections (ArrayList.SubList, ReverseOrderListView, AbstractMap.keySet, AbstractMap.values, HashMap.EntrySet) use the view reference (and not the underlying collection) for detecting self containment, so renderElements should use this instead of root for self.

@Override
public String toString() {
final StableValueImpl<?>[] values = delegate.values().toArray(GENERATOR);
return StableUtil.renderElements(StableMap.this, "StableMap", values);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return StableUtil.renderElements(StableMap.this, "StableMap", values);
return StableUtil.renderElements(this, "StableCollection", values);

Other view collections (ArrayList.SubList, ReverseOrderListView, AbstractMap.keySet, AbstractMap.values, HashMap.EntrySet) use the view reference (and not the underlying collection) for detecting self containment, so renderElements should use this instead of StableMap.this for self. ImmutableCollections.StableMap.StableMapValues is a Collection, not a Map, so use "StableCollection" instead of "StableMap".

*
* @param other to return if the contents is not set
*/
T orElse(T other);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to note that JEP 506 is proposing to change ScopedValue.orElse to disallow null. A ScopedValue can be bound to null (e.g. usage in Subject API) so using orElse(null) is problematic. A orNull may be added later if needed. As a StableValue can hold null then it's similar and might be surprising to developers to have the two APIs be different here. Something to look at again after JEP 502 is integrated, I'm not suggesting changing anything in this PR of course.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yepp. Disallowing null is on the list for exploring in the next preview.

// in a slow path.
private void preventReentry() {
if (Thread.holdsLock(this)) {
throw new IllegalStateException("Recursive initialization of a stable value is illegal");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know how common it is to use holdsLocks for control flow but just to say that there are several places in the JDK that have to detect reentrancy and some of these are good candidates to use ScopedValues.

Copy link
Contributor

@AlanBateman AlanBateman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been through the API + implementation, and a brief scan (not detailed) of the tests. Good job, it will be good to get this integrated and start to get some usage and feedback.

@minborg
Copy link
Contributor Author

minborg commented Apr 25, 2025

Thank you, @lukellmann, for your comments. Some of them were very useful! I will address them after integrating the PR.

Copy link
Member

@liach liach left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the design and the essential implementation meets the "95% complete" bar for preview features. There are some ceremony like toString and some other details like null values, but they should not be serious enough for this to be delivered for preview.

}

@jdk.internal.ValueBased
final class StableMapEntrySet extends AbstractImmutableSet<Map.Entry<K, V>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One concern about the (non-static) inner classes is that we can't stable-annotate the immediately enclosing instance - we might need general trusting for java.util, but we need to ensure users aren't hacking collection final fields first.

@openjdk openjdk bot added ready Pull request is ready to be integrated and removed csr Pull request needs approved CSR before integration labels Apr 29, 2025
Copy link
Member

@JornVernee JornVernee left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks mostly good. Left a few more inline comments

Comment on lines +617 to +618
* @param size the size of the allowed inputs in the continuous
* interval {@code [0, size)}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Size of allowed inputs" doesn't seem quite right, maybe:

Suggested change
* @param size the size of the allowed inputs in the continuous
* interval {@code [0, size)}
* @param size the upper bound of the range {@code [0, size)} indicating the allowed inputs

*
* @param size the size of the allowed inputs in the continuous
* interval {@code [0, size)}
* @param underlying IntFunction used to compute cached values
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @param underlying IntFunction used to compute cached values
* @param underlying {@code IntFunction} used to compute cached values

@MethodSource("allSets")
void factoryInvariants(Set<Value> inputs) {
assertThrows(NullPointerException.class, () -> StableValue.function(null, MAPPER));
assertThrows(NullPointerException.class, () -> StableValue.function(inputs, null));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you also need a case for null elements in inputs

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a separate @Test void nullKeys() that takes care of that case.

}))
.toList();
threads.forEach(Thread::start);
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of parking and calling countDown here, which might be unreliable if a particular thread doesn't get scheduled, you could set the latch value to noThreads, and then do a starter.countDown() before calling await. That should start all the threads running at the same time once all of them are ready.

Comment on lines +115 to +121
Object cp() {
CodeBuilder cob = null;
ConstantPoolBuilder cp = ConstantPoolBuilder.of();
cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA), List.of()),
cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
return null;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems unused

Copy link
Member

@JornVernee JornVernee left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other comments I had weren't as important

@minborg
Copy link
Contributor Author

minborg commented Apr 30, 2025

/integrate

@openjdk
Copy link

openjdk bot commented Apr 30, 2025

Going to push as commit fbc4691.
Since your change was applied there have been 100 commits pushed to the master branch:

Your commit was automatically rebased without conflicts.

@openjdk openjdk bot added the integrated Pull request has been integrated label Apr 30, 2025
@openjdk openjdk bot closed this Apr 30, 2025
@openjdk openjdk bot removed ready Pull request is ready to be integrated rfr Pull request is ready for review labels Apr 30, 2025
@openjdk
Copy link

openjdk bot commented Apr 30, 2025

@minborg Pushed as commit fbc4691.

💡 You may see a message that your pull request was closed with unmerged commits. This can be safely ignored.

@liach
Copy link
Member

liach commented Apr 30, 2025

Congratulations! With the introduction of this as a preview feature, we can slowly improve it over time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core-libs core-libs-dev@openjdk.org integrated Pull request has been integrated

Development

Successfully merging this pull request may close these issues.