Skip to content

Use ParseUtil's precompiled patterns instead of recompiling per call - #3617

Merged
dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:split-sweep
Aug 15, 2026
Merged

dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:split-sweep

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

A mechanical follow-up to #3615 and #3616. No behavior change and no changelog entry.

Twenty splits stop recompiling their pattern

String.split only takes the JDK fast path when the regex is a single character that is not one of .$|()[{^?*+\, or a two-character backslash escape. Anything longer falls through to Pattern.compile(regex).split(this, limit) — a fresh compile on every call. Twenty sites split on \s+ or \D+, both of which ParseUtil already holds as compiled constants, and eleven of them sit inside per-line parsing loops.

- String[] parts = line.split("\\s+", -1);
+ String[] parts = ParseUtil.whitespaces.split(line, -1);

The limit is preserved at each site (nineteen of the twenty carry the , -1 added in #3597), and the receiver moves into the argument unchanged, including the awkward ones such as BsdSysctlUtil.sysctl("hw.disknames", "").trim() and osDescriptors.get(0).

The single-character splits are deliberately left alone

This is the part worth not "fixing" later. There are 83 sites splitting on , : / = and a bare space, and routing those through a precompiled Pattern would make them slower, because Pattern.split allocates a Matcher while the fast path is an indexOf loop. An indicative measurement on JDK 26, splitting a ten-field line two million times after warmup:

split ns/op
"," via String.split (fast path) 103
"," via precompiled Pattern.split 317
"\\s+" via String.split (compiles each call) 491
"\\s+" via precompiled Pattern.split 393

That is a warmed-up loop rather than JMH, so treat the magnitudes as indicative; the direction is what matters, and it is the opposite of the intuition that a precompiled pattern is always better.

Removes ParseUtil.slash

It has no callers anywhere in the project, and its javadoc still called it forwardSlash from a rename. It is also self-defeating: \/ is a two-character escape, so a plain split("/") would take the fast path and beat it. ParseUtil is not annotated @PublicApi, which is what the japicmp configuration includes, so this is outside the compatibility-checked surface.

Guards one static initializer

SolarisOperatingSystem read split[0] without checking the length. Splitting on whitespace returns a zero-length array when the input is entirely whitespace, so a uname -rv first line of only whitespace would have thrown. It is unreachable in practice — getFirstAnswer returns an empty string when the command fails, and splitting that yields a one-element array — but this runs in a static initializer, where an exception leaves the class permanently unusable, so it is cheap insurance.

Not included

Twelve one-off multi-character regexes have no existing constant (, , [()], : , [ \t#;], [,\s]+, [\n\r], \s*=\s*, \s, and two literal separators). Hoisting each to its own private static final Pattern is a judgment call rather than a mechanical one, and only the two inside LinuxOperatingSystem loops would measurably benefit, so they are left for a separate decision.

Verification

Full gate green locally on macOS/JDK 25: ./mvnw clean spotless:apply sortpom:sort checkstyle:check install forbiddenapis:check javadoc:javadoc, plus ./mvnw -Perror-prone install -DskipTests over the whole reactor. 1561 tests pass, with no test changes — the intended outcome for a semantics-preserving sweep, since String.split's slow path is Pattern.compile(regex).split(this, limit).

Summary by CodeRabbit

  • Bug Fixes

    • Improved Solaris version detection when system information is empty or incomplete.
    • Improved reliability when reading firmware, printer, processor, disk, filesystem, network, DNS, and system statistics across supported platforms.
    • Improved processor affinity parsing on NetBSD.
  • Refactor

    • Standardized text parsing across supported platforms for more consistent results and reduced processing overhead.
    • Removed an obsolete parsing utility constant.

String.split only takes the JDK fast path for a single non-metacharacter
regex, or a two-character backslash escape. Anything longer falls through to
Pattern.compile(regex).split(this, limit), which compiles a fresh Pattern on
every invocation. Twenty sites split on \s+ or \D+, which ParseUtil already
holds as compiled constants, and eleven of them are inside per-line loops.

Only those twenty change. The 83 single-character sites are left alone
deliberately: a precompiled Pattern allocates a Matcher, so routing them
through one would be slower than the fast path they take today.

Removes ParseUtil.slash, which has no callers. Its javadoc still named it
forwardSlash from an earlier rename, and as a two-character escape it was
slower than the fast path a plain split would have taken. It is not
@publicapi, which is what japicmp checks.

Also guards the first element in SolarisOperatingSystem's static
initializer. Splitting on whitespace returns a zero-length array for input
that is entirely whitespace, and an exception there would leave the class
unusable.
@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3abb2db1-4423-491f-be76-c7bdd915b02a

📥 Commits

Reviewing files that changed from the base of the PR and between 471eed8 and 049fd4a.

📒 Files selected for processing (1)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (13)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Error Prone
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle)

📝 Walkthrough

Walkthrough

The change replaces repeated local regular-expression compilation with shared or precompiled patterns across hardware, operating system, and utility parsers. It removes the public ParseUtil.slash constant and guards Solaris version parsing against empty uname -rv output.

Changes

Parser cleanup

Layer / File(s) Summary
Shared parsing utilities and consumers
oshi-common/src/main/java/oshi/util/ParseUtil.java, oshi-common/src/main/java/oshi/util/PrivilegedUtil.java, oshi-common/src/main/java/oshi/util/common/platform/unix/netbsd/FstatUtil.java, oshi-common/src/main/java/oshi/util/driver/unix/*, oshi-common/src/main/java/oshi/software/common/AbstractNetworkParams.java, oshi-common/src/main/java/oshi/software/common/os/linux/*, oshi-common/src/main/java/oshi/software/common/os/unix/solaris/SolarisOSProcess.java, oshi-common/src/main/java/oshi/util/EdidUtil.java
Shared whitespace, non-digit, and delimiter patterns replace local expressions. The public ParseUtil.slash pattern is removed.
Platform parser pattern reuse
oshi-common/src/main/java/oshi/hardware/common/platform/unix/*, oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsHWDiskStore.java, oshi-common/src/main/java/oshi/software/common/os/unix/netbsd/NetBsdOSProcess.java
Platform parsers use shared or precompiled patterns without changing existing extraction behavior.
Solaris version parsing guard
oshi-common/src/main/java/oshi/software/common/os/unix/solaris/SolarisOperatingSystem.java
Empty or whitespace-only uname -rv output now produces an empty version instead of indexing a missing token.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to 049fd

This PR makes localized performance-oriented parsing changes without an intended behavior change, and no actionable merge-blocking risk remains beyond normal checks and review.

Possibly related PRs

Poem

A rabbit shares patterns with care,
Across BSD, Linux, and elsewhere.
Solaris checks an empty line,
Old regex calls fall out of time.
“Hop, parse, and reuse!” cries mine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: replacing repeated regular-expression compilation with ParseUtil's precompiled patterns.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Nine more sites compile a regex on every call inside a per-line loop, but
split on something ParseUtil does not already hold. Each gets a private
compiled constant in its own class rather than a new shared one, since the
patterns are specific to the format being parsed.

Named in upper snake case, which satisfies checkstyle's ConstantName; the
lowercase names in ParseUtil are why that file carries a CHECKSTYLE:OFF
block.

Two candidates are deliberately left alone. FreeBsdCentralProcessor's
[\n\r] split runs once from initProcessorCounts on a single large
sysctl blob, so the compile is amortized to nothing, and Xwininfo's
splits its input once and then iterates the result.
Hoisting the second split inside parseRelease made Error Prone start
reporting StringSplitter on the first one, which is pre-existing and
unchanged. Converting the delimiter parameter to a Pattern did not settle
it either: the check still fires on a one-argument split through a Pattern
parameter, though not through a resolvable constant such as
ParseUtil.whitespaces. Adding a limit would be the usual fix but is not
semantics-preserving here, since a line ending in the delimiter would start
reporting an empty version rather than UNKNOWN.

The two hoists that motivated the change are inside the per-line loop and
are kept.
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.95%. Comparing base (5af55c7) to head (049fd4a).

Files with missing lines Patch % Lines
...oftware/common/os/unix/netbsd/NetBsdOSProcess.java 0.00% 3 Missing ⚠️
...shi/hardware/common/platform/unix/BsdFirmware.java 75.00% 0 Missing and 1 partial ⚠️
...common/platform/unix/netbsd/NetBsdHWDiskStore.java 0.00% 1 Missing ⚠️
...common/os/unix/solaris/SolarisOperatingSystem.java 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3617      +/-   ##
============================================
- Coverage     80.02%   79.95%   -0.07%     
- Complexity     3860     3996     +136     
============================================
  Files           696      696              
  Lines         24210    24219       +9     
  Branches       3996     3997       +1     
============================================
- Hits          19373    19365       -8     
- Misses         2713     2730      +17     
  Partials       2124     2124              
Flag Coverage Δ
freebsd 33.56% <56.41%> (-0.01%) ⬇️
linux 37.71% <79.48%> (+0.01%) ⬆️
macos 38.53% <56.41%> (-0.05%) ⬇️
openbsd 32.72% <56.41%> (-0.01%) ⬇️
solaris 34.21% <56.41%> (-0.01%) ⬇️
windows 45.36% <58.97%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dbwiddis
dbwiddis merged commit 675c5c9 into oshi:master Aug 15, 2026
29 of 30 checks passed
@dbwiddis
dbwiddis deleted the split-sweep branch August 15, 2026 01:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant