From 83950bcfb48159aa1517834333b636f74afa1f56 Mon Sep 17 00:00:00 2001 From: Peter Paul Bakker Date: Tue, 24 Nov 2026 13:06:17 +0000 Subject: [PATCH] feat(jre): add opt-in memory_calculator.xms_equals_xmx Forward --xms-equals-xmx to the memory calculator when JBP_CONFIG__JRE sets memory_calculator.xms_equals_xmx: true. Disabled by default; the flag is only passed when enabled, because calculator releases before the one that adds it exit with "unknown flag". Refs #1377 --- docs/IMPLEMENTING_JRES.md | 5 +- docs/jre-open_jdk_jre.md | 14 ++++- src/integration/spring_boot_test.go | 56 +++++++++++++++++ src/java/jres/memory_calculator.go | 10 +++ .../jres/memory_calculator_issues_test.go | 61 +++++++++++++++++++ 5 files changed, 143 insertions(+), 3 deletions(-) diff --git a/docs/IMPLEMENTING_JRES.md b/docs/IMPLEMENTING_JRES.md index 91ee6455f5..8e53383a89 100644 --- a/docs/IMPLEMENTING_JRES.md +++ b/docs/IMPLEMENTING_JRES.md @@ -280,7 +280,7 @@ export PATH=$JAVA_HOME/bin:$PATH Downloads `java-buildpack-memory-calculator` binary. At application start it computes JVM heap/metaspace/stack settings from `$MEMORY_LIMIT`: ``` --Xmx512M -Xms512M -XX:MaxMetaspaceSize=128M -Xss1M -XX:ReservedCodeCacheSize=32M +-Xmx512M -XX:MaxMetaspaceSize=128M -Xss1M -XX:ReservedCodeCacheSize=32M ``` User customization — prefer `JBP_CONFIG__JRE` for structured config (covers all three knobs): @@ -293,8 +293,9 @@ cf set-env myapp JBP_CONFIG_OPEN_JDK_JRE \ `stack_threads` — number of user threads (default: 250); affects `-Xss` heap budget. `class_count` — estimated loaded classes (default: auto-detected); affects `-XX:MaxMetaspaceSize`. `headroom` — percent of total memory to leave unallocated (default: 0). +`xms_equals_xmx` — experimental: set `-Xms` equal to the maximum heap (default: false). Not available as a `MEMORY_CALCULATOR_*` env var. -`MEMORY_CALCULATOR_*` env vars are a simpler alternative, but only cover two of the three knobs. They take precedence over `JBP_CONFIG_*` when both are set: +`MEMORY_CALCULATOR_*` env vars are a simpler alternative, but only cover some of the knobs. They take precedence over `JBP_CONFIG_*` when both are set: ```bash cf set-env myapp MEMORY_CALCULATOR_STACK_THREADS 300 diff --git a/docs/jre-open_jdk_jre.md b/docs/jre-open_jdk_jre.md index ce27d4785b..b96273bb00 100644 --- a/docs/jre-open_jdk_jre.md +++ b/docs/jre-open_jdk_jre.md @@ -81,7 +81,7 @@ The total available memory for the application's container is specified when an The Java buildpack uses this value to control the JRE's use of various regions of memory and logs the JRE memory settings when the application starts or restarts. These settings can be influenced by configuring -the `stack_threads` and/or `class_count` mappings (both part of the `memory_calculator` mapping), +the `stack_threads`, `class_count`, `headroom` and/or `xms_equals_xmx` mappings (all part of the `memory_calculator` mapping), and/or Java options relating to memory. Note: If the total available memory is scaled up or down, the Java buildpack will re-calculate the JRE memory settings the next time the application is started. @@ -119,6 +119,18 @@ stack_threads: 500 Note that the default value of 250 threads is optimized for a default Tomcat configuration. If you are using another container, especially something non-blocking like Netty, it's more appropriate to use a significantly smaller value. Typically 25 threads would cover the needs of both the server (Netty) and the threads started by the JVM itself. +#### Initial Heap + +By default the memory calculator sets only the maximum heap size (`-Xmx`) and the JVM chooses the initial heap size, which grows under load. To set the initial heap size (`-Xms`) equal to the maximum heap size, enable the experimental `xms_equals_xmx` option: + +```yaml +xms_equals_xmx: true +``` + +An explicit `-Xms` in the Java options takes precedence. If an explicit `-Xms` is larger than the maximum heap, the application fails to start with an error from the memory calculator. + +Setting the initial heap equal to the maximum heap avoids heap growth, but increases the initially committed memory and can affect memory-based autoscaling. Compare latency, GC pauses, CPU and container memory under a representative workload before enabling it in production. + #### Java Options If the JRE memory settings need to be fine-tuned, the user can set one or more Java memory options to diff --git a/src/integration/spring_boot_test.go b/src/integration/spring_boot_test.go index b5e53d14e6..ba2d2d6acf 100644 --- a/src/integration/spring_boot_test.go +++ b/src/integration/spring_boot_test.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "net/http" + "strings" "testing" "github.com/cloudfoundry/switchblade" @@ -13,6 +14,26 @@ import ( . "github.com/onsi/gomega" ) +type heapOptions struct { + Xms string + Xmx string +} + +func heapOptionsOf(inputArguments string) heapOptions { + var heap heapOptions + for _, argument := range strings.FieldsFunc(inputArguments, func(r rune) bool { + return r == '"' || r == ',' || r == '[' || r == ']' || r == ' ' || r == '\n' + }) { + if value, found := strings.CutPrefix(argument, "-Xms"); found { + heap.Xms = value + } + if value, found := strings.CutPrefix(argument, "-Xmx"); found { + heap.Xmx = value + } + } + return heap +} + func testSpringBoot(platform switchblade.Platform, fixtures string, sb3JarPath, sb4JarPath string) func(*testing.T, spec.G, spec.S) { return func(t *testing.T, context spec.G, it spec.S) { var ( @@ -77,6 +98,41 @@ func testSpringBoot(platform switchblade.Platform, fixtures string, sb3JarPath, }) }) + // https://github.com/cloudfoundry/java-buildpack/issues/1377 + context("with the memory calculator", func() { + it("sets the initial heap equal to the maximum heap when xms_equals_xmx is true", func() { + deployment, logs, err := platform.Deploy. + WithEnv(map[string]string{ + "BP_JAVA_VERSION": defaultJavaVersion, + "JBP_CONFIG_OPEN_JDK_JRE": "{ memory_calculator: { xms_equals_xmx: true } }", + }). + Execute(name, requireJar(t, sb4JarPath)) + Expect(err).NotTo(HaveOccurred(), logs.String) + + Eventually(deployment).Should(matchers.Serve( + WithTransform(heapOptionsOf, Satisfy(func(heap heapOptions) bool { + return heap.Xmx != "" && heap.Xms == heap.Xmx + })), + ).WithEndpoint("/input-arguments")) + }) + + it("does not set an initial heap by default", func() { + deployment, logs, err := platform.Deploy. + WithEnv(map[string]string{ + "BP_JAVA_VERSION": defaultJavaVersion, + }). + Execute(name, requireJar(t, sb4JarPath)) + Expect(err).NotTo(HaveOccurred(), logs.String) + + Eventually(deployment).Should(matchers.Serve( + WithTransform(heapOptionsOf, And( + HaveField("Xmx", Not(BeEmpty())), + HaveField("Xms", BeEmpty()), + )), + ).WithEndpoint("/input-arguments")) + }) + }) + context("with JAVA_OPTS configuration", func() { it("applies configured JAVA_OPTS with from_environment=false and verifies at runtime", func() { deployment, logs, err := platform.Deploy. diff --git a/src/java/jres/memory_calculator.go b/src/java/jres/memory_calculator.go index 7477063513..fa2bf40990 100644 --- a/src/java/jres/memory_calculator.go +++ b/src/java/jres/memory_calculator.go @@ -25,6 +25,7 @@ type MemoryCalculator struct { classCount int stackThreads int headroom int + xmsEqualsXmx bool configLoaded bool classCountUserSet bool stackThreadsUserSet bool @@ -124,6 +125,9 @@ func (m *MemoryCalculator) Supply() error { m.ctx.Log.Info("Memory Calculator installed: Loaded Classes: %s, Threads: %s, Headroom: %s", m.classCountDisplay(), m.stackThreadsDisplay(), m.headroomDisplay()) + if m.xmsEqualsXmx { + m.ctx.Log.Info("Memory Calculator: initial heap (-Xms) equals maximum heap (-Xmx)") + } // Clean up temp directory os.RemoveAll(tempDir) @@ -296,6 +300,10 @@ func (m *MemoryCalculator) GetCalculatorCommand() string { classCount = int(float64(DefaultClassCount) * 0.35) // Apply same 35% factor } + if m.xmsEqualsXmx { + args = append(args, "--xms-equals-xmx") + } + args = append(args, fmt.Sprintf("--loaded-class-count=%d", classCount), fmt.Sprintf("--thread-count=%d", m.stackThreads), @@ -330,6 +338,7 @@ type memoryCalculatorConfig struct { StackThreads int `yaml:"stack_threads"` ClassCount int `yaml:"class_count"` Headroom int `yaml:"headroom"` + XmsEqualsXmx bool `yaml:"xms_equals_xmx"` } // LoadConfig loads memory calculator configuration from the JRE-specific env var @@ -383,6 +392,7 @@ func (m *MemoryCalculator) LoadConfig() { m.headroom = mc.Headroom m.headroomUserSet = true } + m.xmsEqualsXmx = mc.XmsEqualsXmx } } diff --git a/src/java/jres/memory_calculator_issues_test.go b/src/java/jres/memory_calculator_issues_test.go index 5fb7e36ca1..7fb3a1027d 100644 --- a/src/java/jres/memory_calculator_issues_test.go +++ b/src/java/jres/memory_calculator_issues_test.go @@ -280,4 +280,65 @@ var _ = Describe("Memory Calculator Issues", func() { "MALLOC_ARENA_MAX must be exported to reach the exec-ed JVM.\nCommand:\n%s", cmd) }) }) + + // ------------------------------------------------------------------------- + // https://github.com/cloudfoundry/java-buildpack/issues/1377 + // Opt-in memory_calculator.xms_equals_xmx forwards --xms-equals-xmx to the calculator. + // Calculator versions before the one that introduced the flag exit with + // "unknown flag", so the flag must only be passed when the user opts in. + // ------------------------------------------------------------------------- + Describe("#1377: xms_equals_xmx", func() { + commandFor := func(jreName string) string { + fakeBinary("4.2.0") + mc := jres.NewMemoryCalculator(ctx, jreDir, "17.0.9", 17, jreName) + Expect(mc.Finalize()).To(Succeed()) + return mc.GetCalculatorCommand() + } + + It("does not pass --xms-equals-xmx by default", func() { + Expect(commandFor("openjdk")).NotTo(ContainSubstring("xms-equals-xmx")) + }) + + It("passes --xms-equals-xmx when JBP_CONFIG_OPEN_JDK_JRE sets xms_equals_xmx: true", func() { + DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE") + Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", "{ memory_calculator: { xms_equals_xmx: true } }")).To(Succeed()) + + Expect(commandFor("openjdk")).To(ContainSubstring("--xms-equals-xmx")) + }) + + It("does not pass --xms-equals-xmx when xms_equals_xmx: false", func() { + DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE") + Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", "{ memory_calculator: { xms_equals_xmx: false } }")).To(Succeed()) + + Expect(commandFor("openjdk")).NotTo(ContainSubstring("xms-equals-xmx")) + }) + + It("passes --xms-equals-xmx for another JRE through its own JBP_CONFIG variable", func() { + DeferCleanup(os.Unsetenv, "JBP_CONFIG_ZULU_JRE") + Expect(os.Setenv("JBP_CONFIG_ZULU_JRE", "{ memory_calculator: { xms_equals_xmx: true } }")).To(Succeed()) + + Expect(commandFor("zulu")).To(ContainSubstring("--xms-equals-xmx")) + }) + + It("passes the flag together with the other memory_calculator settings", func() { + DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE") + Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", + "{ memory_calculator: { xms_equals_xmx: true, headroom: 5, stack_threads: 50 } }")).To(Succeed()) + + cmd := commandFor("openjdk") + + Expect(cmd).To(ContainSubstring("--xms-equals-xmx")) + Expect(cmd).To(ContainSubstring("--head-room=5")) + Expect(cmd).To(ContainSubstring("--thread-count=50")) + }) + + It("accepts xms_equals_xmx without an unknown-field WARNING", func() { + DeferCleanup(os.Unsetenv, "JBP_CONFIG_OPEN_JDK_JRE") + Expect(os.Setenv("JBP_CONFIG_OPEN_JDK_JRE", "{ memory_calculator: { xms_equals_xmx: true } }")).To(Succeed()) + + commandFor("openjdk") + + Expect(logBuffer.String()).NotTo(ContainSubstring("WARNING")) + }) + }) })