JDK-8310011 : Arena with try-with-resources is slower than it should be
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang.foreign
  • Affected Version: 20,21,22
  • Priority: P3
  • Status: Closed
  • Resolution: Fixed
  • Submitted: 2023-06-14
  • Updated: 2024-02-20
  • Resolved: 2023-11-28
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 22
22 b26Fixed
Related Reports
Relates :  
Description
We have a microbenchmark to test the performance of a strlen call using panama. One such benchmark is:

    @Benchmark
    public int panama_strlen() throws Throwable {
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment segment = arena.allocateUtf8String(str);
            return (int)STRLEN.invokeExact(segment);
        }
    }

Here, we create a confined arena, allocate a string using the arena, then pass the string segment to the native function. This is a very idiomatic usage of the FFM API.

However, benchmarks reveal that the usage of try with resources here creates problems. That is, this benchmark come up at 100ns/op. But, if the code is rearranged as follows:

    @Benchmark
    public int panama_strlen() throws Throwable {
            Arena arena = Arena.ofConfined();
            MemorySegment segment = arena.allocateUtf8String(str);
            int res = (int)STRLEN.invokeExact(segment);
            arena.close();
            return res;
        }
    }

Then the benchmark scores improves to 86ns/op. I have been able to reproduce similar numbers in other cases where a try-with-resources was used.

It would be nice if users didn't have to choose between code clarity and performance.
Comments
Changeset: a5ccd3be Author: Jorn Vernee <jvernee@openjdk.org> Date: 2023-11-28 10:17:58 +0000 URL: https://git.openjdk.org/jdk/commit/a5ccd3beaf069bdfe81736f6c62e5b4b9e18b5fe
28-11-2023

A pull request was submitted for review. URL: https://git.openjdk.org/jdk/pull/16416 Date: 2023-10-30 14:10:33 +0000
01-11-2023