Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8345668: ZoneOffset.ofTotalSeconds performance regression #22854

Closed

Conversation

naotoj
Copy link
Member

@naotoj naotoj commented Dec 20, 2024

The change made in JDK-8288723 seems innocuous, but it caused this performance regression. Partially reverting the change (ones that involve computeIfAbsent()) to the original. Provided a benchmark that iterates the call to ZoneOffset.ofTotalSeconds(0) 1,000 times, which improves the operation time from 3,946ns to 2,241ns.


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

Issue

  • JDK-8345668: ZoneOffset.ofTotalSeconds performance regression (Bug - P3)

Reviewers

Reviewing

Using git

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

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

Using Skara CLI tools

Checkout this PR locally:
$ git pr checkout 22854

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

Using diff file

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

Using Webrev

Link to Webrev Comment

@bridgekeeper
Copy link

bridgekeeper bot commented Dec 20, 2024

👋 Welcome back naoto! A progress list of the required criteria for merging this PR into master will be added to the body of your pull request. There are additional pull request commands available for use with this pull request.

@openjdk
Copy link

openjdk bot commented Dec 20, 2024

@naotoj This change now passes all automated pre-integration checks.

ℹ️ This project also has non-automated pre-integration requirements. Please see the file CONTRIBUTING.md for details.

After integration, the commit message for the final commit will be:

8345668: ZoneOffset.ofTotalSeconds performance regression

Reviewed-by: rriggs, aturbanov

You can use pull request commands such as /summary, /contributor and /issue to adjust it as needed.

At the time when this comment was updated there had been 3 new commits pushed to the master branch:

  • a77ed30: 8336412: sun.net.www.MimeTable has a few unused methods
  • e769b53: 8346193: CrashGCForDumpingJavaThread do not trigger expected crash build with clang17
  • a87bc7e: 8345374: Ubsan: runtime error: division by zero

Please see this link for an up-to-date comparison between the source branch of this pull request and the master branch.
As there are no conflicts, your changes will automatically be rebased on top of these commits when integrating. If you prefer to avoid this automatic rebasing, please check the documentation for the /integrate command for further details.

➡️ To integrate this PR with the above commit message to the master branch, type /integrate in a new comment.

@openjdk openjdk bot added the rfr Pull request is ready for review label Dec 20, 2024
@openjdk
Copy link

openjdk bot commented Dec 20, 2024

@naotoj The following labels will be automatically applied to this pull request:

  • core-libs
  • i18n

When this pull request is ready to be reviewed, an "RFR" email will be sent to the corresponding mailing lists. If you would like to change these labels, use the /label pull request command.

@openjdk openjdk bot added core-libs core-libs-dev@openjdk.org i18n i18n-dev@openjdk.org labels Dec 20, 2024
@mlbridge
Copy link

mlbridge bot commented Dec 20, 2024

Webrevs

naotoj and others added 2 commits December 20, 2024 12:54
return SECONDS_CACHE.computeIfAbsent(totalSeconds, totalSecs -> {
ZoneOffset result = new ZoneOffset(totalSecs);
Integer totalSecs = totalSeconds;
ZoneOffset result = SECONDS_CACHE.get(totalSecs);
Copy link
Contributor

Choose a reason for hiding this comment

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

Here, each call may allocate an Integer object. The maximum number of ZoneOffsets that need to be cached here is only 148. Using AtomicReferenceArray is better than AtomicConcurrentHashMap.

Copy link
Contributor

@wenshao wenshao Dec 20, 2024

Choose a reason for hiding this comment

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

For example:

static final AtomicReferenceArray<ZoneOffset> MINUTES_15_CACHE = new AtomicReferenceArray<>(37 * 4);

    public static ZoneOffset ofTotalSeconds(int totalSeconds) {
        // ...
        int minutes15Rem = totalSeconds / (15 * SECONDS_PER_MINUTE);
        if (totalSeconds - minutes15Rem * 15 * SECONDS_PER_MINUTE == 0) {
            int cacheIndex = minutes15Rem + 18 * 4;
            ZoneOffset result = MINUTES_15_CACHE.get(cacheIndex);
            if (result == null) {
                result = new ZoneOffset(totalSeconds);
                if (!MINUTES_15_CACHE.compareAndSet(cacheIndex, null, result)) {
                    result = MINUTES_15_CACHE.get(minutes15Rem);
                }
            }
            return result;
        }
       // ...
    }

Copy link
Member Author

@naotoj naotoj Dec 20, 2024

Choose a reason for hiding this comment

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

Hi Shaojin,
Thanks for the suggestion, but I am not planning to improve the code more than backing out the offending fix at this time. (btw, cache size would be 149 as 18:00 and -18:00 are inclusive)

Copy link
Contributor

Choose a reason for hiding this comment

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

Can I submit a PR to make this improvement?

Copy link
Member

@liach liach Dec 21, 2024

Choose a reason for hiding this comment

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

@wenshao I agree with your proposal. Also for this part:

ZoneOffset result = MINUTES_15_CACHE.get(cacheIndex);
if (result == null) {
    result = new ZoneOffset(totalSeconds);
    if (!MINUTES_15_CACHE.compareAndSet(cacheIndex, null, result)) {
        result = MINUTES_15_CACHE.get(minutes15Rem);
    }
}

I recommend a rewrite:

ZoneOffset result = MINUTES_15_CACHE.getPlain(cacheIndex);
if (result == null) {
    result = new ZoneOffset(totalSeconds);
    ZoneOffset existing = MINUTES_15_CACHE.compareAndExchange(cacheIndex, null, result);
    return existing == null ? result : existing;
}

The getPlain is safe because ZoneOffset is thread safe, so you can use the object when you can observe a ZoneOffset object reference. Also compareAndExchange avoids extra operations if we failed to racily set the computed ZoneOffset.

@Benchmark
public void ofTotalSeconds() {
for (int i = 0; i < 1_000; i++) {
ZoneOffset.ofTotalSeconds(0);
Copy link
Member

Choose a reason for hiding this comment

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

This benchmark method should accept a Blackhole, and the return value of ofTotalSeconds must be sent to the Blackhole.consume method.

Copy link
Member

Choose a reason for hiding this comment

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

This benchmark currently works probably because the cache interactions in ofTotalSeconds, which means JIT compilation cannot prove it is side-effect free. Had it been as simple as a decimal computation or if the cache becomes a stable map, JIT compilation can eliminate the static factory method call entirely, and the benchmark would be measuring the performance of no-op invocation.

Copy link
Member Author

Choose a reason for hiding this comment

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

I decided to remove this benchmark, as the fix is merely to revert the previous fix and not providing any performance improvement (to the original).

@liach
Copy link
Member

liach commented Dec 21, 2024

The putIfAbsent remark from Roger Riggs applies to DateTimeTextProvider and DecimalStyle too. I think reusing existing result in these two places is beneficial, as the replaced computeIfAbsent returns the same object identity which may be helpful for quick equals comparisons.

Comment on lines 314 to 316
store = createStore(field, locale);
CACHE.putIfAbsent(key, store);
store = CACHE.get(key);
Copy link
Contributor

Choose a reason for hiding this comment

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

should this be
store = CACHE.computeIfAbsent(key, e -> createStore(e.getKey(), e.getValue()));

That still allow the optimistic/concurrent get call to succeed most of the time (when already cached) but reduce the interactions with the map when a value is created/set/accessed the first time.

Alternatively, the result of putIfAbsent could be checked/used to avoid the second call to get.

Copy link
Member

Choose a reason for hiding this comment

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

For sure we should use result of putIfAbsent. Let's do this for all cases. See how it was implemented in my first commit - 73a2f6c

Copy link
Contributor

Choose a reason for hiding this comment

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

For sure we should use result of putIfAbsent

Drive-by comment...

From what i can infer, the performance regression being addressed here is caused in part by the fact that (for example) ConcurrentHashMap.computeIfAbsent() provides an atomicity guarantee, which is a stronger requirement than is necessary here, and therefore by splitting up that call up into two separate, non-atomic get() and put() calls we get (counter-intuitively) faster execution time, even though there are more lines of code. Note putIfAbsent() also guarantees atomicity, so the same problem of slowness caused by "unnecessary atomicity" might occur with it as well.

Copy link
Member

Choose a reason for hiding this comment

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

Indeed, just noticed that both computeIfAbsent and putIfAbsent may acquire the lock when the key is present, while get never acquires a lock for read-only access.

Maybe the implementation was written back when locking was less costly (with biased locking, etc.). Now we might have to reconsider locking until we know for sure a plain get fails.

Copy link
Contributor

Choose a reason for hiding this comment

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

This scenario is discussed in Effective Java by Joshua Block. His observation then (java 5/6 time frame?) was optimistically calling get first and only calling putIfAbsent or computeIfAbsent if the get returned null was 250% faster, and this is because calls to put/compute ifAbsent have contention. There have been changes made to those methods since then to try to avoid synchronization when the key is already present, but the observation seems to confirm that the optimistic get call first is still faster (though a much smaller difference).

My comment was not to revert back to the prior change of just calling computeIfAbsent, but rather just to change the (expected rare) case when the first get returns null to replace the putIfAbsent and second get call with a single computeIfAbsent (or utilize the result of putIfAbsent to avoid the second call to get).

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks for your observations. I think Archie's analysis sounds right, although have not confirmed. Will use the result from putIfAbsent() for all cases.

Copy link
Contributor

@RogerRiggs RogerRiggs left a comment

Choose a reason for hiding this comment

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

Looks good to me.

@openjdk openjdk bot added the ready Pull request is ready to be integrated label Jan 2, 2025
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved.
Copy link
Member

Choose a reason for hiding this comment

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

Shouldn't be 2025 too?

Copy link
Member Author

Choose a reason for hiding this comment

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

This PR was published last year and ZoneOffset has not changed since then. So I think 2024 is fine

@naotoj
Copy link
Member Author

naotoj commented Jan 6, 2025

Thank you for the reviews!
/integrate

@openjdk
Copy link

openjdk bot commented Jan 6, 2025

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

  • 12700cb: 8346264: "Total compile time" counter should include time spent in failing/bailout compiles
  • dd81f8d: 8344079: Minor fixes and cleanups to compiler lint-related code
  • ccf3d57: 8346985: Convert test/jdk/com/sun/jdi/ClassUnloadEventTest.java to Class-File API
  • 594e519: 8346984: Remove ASM-based benchmarks from Class-File API benchmarks
  • c027f2e: 8346983: Remove ASM-based transforms from Class-File API tests
  • e0695e0: 8346981: Remove obsolete java.base exports of jdk.internal.objectweb.asm packages
  • dfaa891: 8346569: Shenandoah: Worker initializes ShenandoahThreadLocalData twice results in memory leak
  • f1d85ab: 8346773: Fix unmatched brackets in some misc files
  • 9393897: 8346260: Test "javax/swing/JOptionPane/bug4174551.java" failed because the font size of message "Hi 24" is not set to 24 in Nimbus LookAndFeel
  • e98f412: 8346922: TestVectorReinterpret.java fails without the rvv extension on RISCV fastdebug VM
  • ... and 6 more: https://git.openjdk.org/jdk/compare/d3abf01c3e8236d37ec369429e17f35afeb7ab88...master

Your commit was automatically rebased without conflicts.

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

openjdk bot commented Jan 6, 2025

@naotoj Pushed as commit 9a60f44.

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

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 i18n i18n-dev@openjdk.org integrated Pull request has been integrated
Development

Successfully merging this pull request may close these issues.

7 participants