On Mon, 30 Mar 2026 16:58:28 GMT, Ruby Chen <[email protected]> wrote:

> When comparing a `MemorySegment` to `MemorySegment.NULL` using `==`, the 
> comparison may fail because a segment with address `0` can be created 
> independently and will therefore have a different identity from 
> `MemorySegment.NULL`. 
> 
> This PR adds JavaDocs that explain this issue and warn against using `==` to 
> compare segments to `MemorySegment.NULL`.

Great work! Left some comments.

src/java.base/share/classes/java/lang/foreign/MemorySegment.java line 1556:

> 1554:      * the {@code NULL} segment is of 2<sup>62</sup>.
> 1555:      *
> 1556:      * @apiNote Clients should avoid using {@code ==} to compare a 
> segment with

I think this is probably the only place where you need the comment. I don't 
think adding this to `ofAddress` helps, as `ofAddress` is only one way to get a 
segment with address `0`. There's other ways such as `reinterpret`, maybe on 
some memory segment returned by a foreign call.

The main point we want to raise here is that NULL is not unique.

src/java.base/share/classes/java/lang/foreign/MemorySegment.java line 1558:

> 1556:      * @apiNote Clients should avoid using {@code ==} to compare a 
> segment with
> 1557:      *          {@code MemorySegment.NULL}. A segment with address 
> {@code 0L} may be
> 1558:      *          created independently and may therefore have a 
> different identity

"created independently" -- I would use `{@linkplain #ofAddress(long) created 
independently}` so that the text also points to one of the problematic methods.

src/java.base/share/classes/java/lang/foreign/MemorySegment.java line 1559:

> 1557:      *          {@code MemorySegment.NULL}. A segment with address 
> {@code 0L} may be
> 1558:      *          created independently and may therefore have a 
> different identity
> 1559:      *          from {@code MemorySegment.NULL}. Furthermore, if {@code 
> MemorySegment}

I think we can lose the para that starts with `Furthemore...`. When Valhalla 
lands, we can revisit.

-------------

PR Review: https://git.openjdk.org/jdk/pull/30501#pullrequestreview-4035904798
PR Review Comment: https://git.openjdk.org/jdk/pull/30501#discussion_r3014578058
PR Review Comment: https://git.openjdk.org/jdk/pull/30501#discussion_r3014583356
PR Review Comment: https://git.openjdk.org/jdk/pull/30501#discussion_r3014586241

Reply via email to