JVM in Containers: Cgroup Memory Limits and Heap Sizing

A guide to how the JVM detects container memory limits, configures heap accordingly, and avoids pitfalls when running Java in Docker and Kubernetes.

published: reading time: 24 min read author: Geek Workbench
Quick Summary

A guide to how the JVM detects container memory limits, configures heap accordingly, and avoids pitfalls when running Java in Docker and Kubernetes.

JVM in Containers: Cgroup Memory Limits and Heap Sizing

For a long time, running Java in a container meant dealing with a painful mismatch. The JVM would report the host’s total memory to Runtime.getRuntime().maxMemory(), not the container’s limit. Deploy a 4GB Java app into a Docker container with a 512MB limit and the JVM would happily try to use far more memory than the container had, leading to OOM kills, eviction, and confusing failures.

Container awareness depends on the JDK build and the host cgroup version. HotSpot added Linux container support in JDK 10; vendor builds backported it to some Java 8 updates. Cgroup v2 support arrived in later updates, so a major version number alone is not enough to tell whether a runtime reads the limit correctly.

This covers how the JVM detects container limits, how to configure heap sizing correctly, and what to watch for in production containerized environments. For broader JVM internals, see JVM architecture overview.

Introduction

Older JVM builds could size themselves from host memory even when the process ran under a Linux cgroup limit. Current behavior depends on the JDK vendor, update level, cgroup version, and runtime configuration. Check those together before relying on automatic sizing.

A container memory limit constrains the processes in its cgroup. When the group reaches the limit, the kernel may reclaim memory or invoke the OOM killer. A small Java heap does not rule out an OOM event: the process also uses native memory.

This guide covers cgroup detection, heap sizing, and the non-heap memory that shares the container budget. It also shows a small container check you can run with the same JDK image you plan to deploy.

How Cgroups Work with Memory

Linux cgroups (control groups) are the mechanism by which the kernel limits and accounts for resource usage of processes. Memory cgroups track how much memory a group of processes is using and can enforce hard limits.

graph TD
    A[Container Process<br/>cgroup=/docker/abc123] --> B[memory.max<br/>= 512m]
    A --> C[memory.current<br/>= 300m]
    B --> D[Kernel Memory<br/>Accounting]
    C --> D
    D --> E{JVM Heap<br/>Allocation}
    E -->|Requests 2GB| F[OOM Kill<br/>Triggered]
    E -->|Requests 256MB| G[Success]
    F --> H[Container Killed]
    G --> I[Container Runs]

When a container is created with a memory limit, the kernel tracks memory usage in the container’s cgroup. If processes in that container try to allocate beyond the limit, the kernel either reclaims memory (if swap is available) or triggers an OOM killer for the offending process.

The JVM needs to know about these limits so it can size its heap appropriately. Without cgroup awareness, Runtime.getRuntime().maxMemory() returns the machine’s total RAM, not the container’s.

JVM Cgroup Detection

HotSpot reads Linux cgroup values when container support is enabled. The table gives upstream OpenJDK/HotSpot reference points; vendor builds can differ, so check the exact runtime image and update.

Cgroup version OpenJDK / HotSpot reference point Notes
v1 JDK 10; container support was backported to Java 8 updates, including 8u191 Check vendor release notes and UseContainerSupport; support may be disabled or patched differently.
v2 JDK 15+, 11.0.16+, and 8u372+ Kubernetes also lists vendor-specific minimums; IBM Semeru, for example, has its own update levels.

These are compatibility reference points, not a guarantee for every vendor build. Kubernetes maintains a cgroup v2 compatibility list. On Linux, identify the node’s cgroup version with stat -fc %T /sys/fs/cgroup/; cgroup2fs indicates v2.

# These are example cgroup files; the mounted path varies by runtime and cgroup layout
# Memory limit
cat /sys/fs/cgroup/memory/memory.limit_in_bytes
# Or for cgroup v2
cat /sys/fs/cgroup/memory.max

# Current memory usage
cat /sys/fs/cgroup/memory/memory.usage_in_bytes
# Or for cgroup v2
cat /sys/fs/cgroup/memory.current

The JVM uses detected limits as input to ergonomics such as MaxRAMPercentage. The effective maximum heap also depends on explicit flags, other JVM ergonomics, and the exact runtime build. Inspect the running image instead of assuming a fixed fraction.

You can verify what the JVM sees by checking the diagnostic flags.

# Print effective JVM ergonomics including container detection
java -XX:+PrintFlagsFinal -version 2>&1 | grep -i "container\|heap"

# Run with container awareness tracing
java -Xlog:os+container=info -Xmx512m -jar myapp.jar

The flag shows whether container support is enabled; it does not by itself prove the JVM read the expected limit. Check the container log output and compare the reported limit with the runtime configuration. The unified logging tag is os+container; event details vary across JDK versions.

Container Memory Flags

Docker and Kubernetes let you set memory limits that the JVM should respect.

# Docker: 512MB container memory limit
docker run -m 512m openjdk:17 java -jar myapp.jar

# Kubernetes: equivalent pod spec
# resources:
#   limits:
#     memory: 512Mi
#   requests:
#     memory: 256Mi

For a 512 MiB container, do not infer a heap size by multiplying the limit by a fixed fraction. Verify the effective heap in the exact image and leave measured headroom for Metaspace, thread stacks, direct buffers, code cache, JNI/native allocations, and agents.

This automatic behavior is usually correct, but there are edge cases where you need to override it.

When to Use

Automatic sizing can be a useful starting point when the exact JDK build supports the host cgroup version and reports the expected limit. Confirm both conditions in the deployed image before relying on it.

Reach for -XX:MaxRAMPercentage when you want predictable heap sizing rather than depending on JVM defaults that vary between Java versions. If you have a multi-version deployment strategy or run across a fleet with different Java versions, explicit percentages keep behavior consistent.

Override the defaults when your application has significant off-heap memory usage. Native buffers, JNI allocations, and memory-mapped files all consume container memory without being counted in the heap. If your application uses 200MB of direct buffers, a 512MB container with a 128MB heap leaves only 384MB for everything else, which may not be enough. In that case, set the heap to something like 1/3 or 1/2 of container memory so combined usage stays within the limit.

Use explicit -Xmx values when you need consistent heap sizing across different container sizes in an autoscaling environment. Auto-sized heaps grow and shrink with container limits, which can lead to the same application behaving differently depending on which pod it lands in.

When NOT to Use

Do not infer container support from “Java 8” or a major version alone. Some Java 8 updates include backports, while some vendor builds or cgroup v2 combinations need a later update. Check the vendor documentation, inspect the runtime, and set an explicit heap cap when detection is unavailable or unverified.

Do not assume a default heap percentage leaves enough room for your workload. Measure peak heap, metaspace, stacks, direct buffers, code cache, JNI allocations, and native agents under representative load, then choose a heap cap with headroom for the rest.

Do not set the container limit equal to -Xmx: the heap is only one part of process memory. There is no universal headroom percentage; measure the other allocations and leave capacity for their peaks.

Do not assume container detection works correctly on all Kubernetes distributions and container runtimes. Some older setups expose missing or incorrect cgroup values. Always verify with -Xlog:os+container=info in staging before betting on automatic detection in production.

Off-Heap Memory Considerations

The JVM uses memory beyond the heap for several components. When sizing a container, you must account for all of it.

graph TD
    A[Container Memory Limit<br/>e.g., 512MB] --> B[Metaspace<br/>~50-100MB]
    A --> C[Thread Stacks<br/>~1MB × num_threads]
    A --> D[Code Cache<br/>~50MB]
    A --> E[Direct Buffers<br/>NIO ByteBuffers]
    A --> F[JVM Internal<br/>Structures]
    A --> G[Heap<br/>Remaining]
    G -->|Default 25%| H[~128MB]
    G -->|With -Xmx256m| I[256MB]
    style G color:#000

For any container size, the usable heap is less than the full memory limit because the process also needs native memory. The amount varies with class loading, thread count, buffers, JNI libraries, agents, and garbage collector. Measure a representative peak instead of applying a universal heap-to-container ratio.

Production Failure Scenarios

Failure Scenario Symptoms Root Cause Solution
OOM kill despite small heap Container killed, exit code 137 JVM using more memory than container limit (Metaspace, buffers) Reduce heap, increase container limit, or limit off-heap usage
JVM not respecting container limit maxMemory() returns host RAM Unsupported vendor/update or cgroup layout, or flags override detection Upgrade to a supported build or set a measured heap cap
Inconsistent heap across pods Different pod uses different heap Auto-scaling creates pods with different limits Use explicit -Xmx rather than auto-sizing
Swap thrashing Container slowing dramatically Container at memory limit, kernel swapping Set --memory-swap equal to --memory, or add more RAM
Native memory exhaustion UnsatisfiedLinkError or native OOM Native allocations not counted in heap Use -XX:MaxNativeHeapSize or profile with NativeMemoryTracking

Trade-off Analysis

Understanding the tradeoffs helps you decide how to configure containers for Java workloads.

Aspect Auto Heap Sizing Explicit -Xmx
Simplicity Lower configuration burden More flags to manage
Consistency Varies with container size Same across all deployments
Off-heap tolerance May oversubscribe memory Tunable for off-heap usage
Multi-version support Auto-adjusts per pod May need different values per Java version
Debugging maxMemory() is informative May need additional flags to verify

Implementation Snippets

Checking JVM Container Awareness at Runtime

public class ContainerMemoryInfo {

    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();

        long maxMemory = runtime.maxMemory();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long usedMemory = totalMemory - freeMemory;

        System.out.println("Max Memory (JVM sees): " + format(maxMemory));
        System.out.println("Total Memory: " + format(totalMemory));
        System.out.println("Used Memory: " + format(usedMemory));

        // Get container limits from the OS
        System.out.println("Container memory limit: " + getContainerLimit());
        System.out.println("Container memory usage: " + getContainerUsage());

        // Check if container support is enabled
        String support = System.getProperty("jdk.container.support", "unknown");
        System.out.println("Container support: " + support);
    }

    private static String format(long bytes) {
        long mb = bytes / (1024 * 1024);
        return mb + " MB";
    }

    private static long getContainerLimit() {
        try {
            // Try cgroup v2 first
            return Long.parseLong(readFile(
                "/sys/fs/cgroup/memory.max").trim());
        } catch (Exception e1) {
            try {
                // Fall back to cgroup v1
                return Long.parseLong(readFile(
                    "/sys/fs/cgroup/memory/memory.limit_in_bytes").trim());
            } catch (Exception e2) {
                return -1;  // Not in a container or unknown
            }
        }
    }

    private static long getContainerUsage() {
        try {
            return Long.parseLong(readFile(
                "/sys/fs/cgroup/memory.current").trim());
        } catch (Exception e1) {
            try {
                return Long.parseLong(readFile(
                    "/sys/fs/cgroup/memory/memory.usage_in_bytes").trim());
            } catch (Exception e2) {
                return -1;
            }
        }
    }

    private static String readFile(String path) throws Exception {
        return java.nio.file.Files.readString(
            java.nio.file.Paths.get(path));
    }
}

Docker Compose Configuration for Java

# docker-compose.yml
version: "3.8"
services:
  myapp:
    image: openjdk:17-slim
    mem_limit: 512m
    # Alternative: mem_reservation (soft limit)
    mem_reservation: 256m
    environment:
      # Override auto-detection if needed
      - JAVA_OPTS=-XX:MaxRAMPercentage=50.0
    deploy:
      resources:
        limits:
          memory: 512M
        reservations:
          memory: 256M
    command: java -XX:+UseContainerSupport -jar /app/myapp.jar

Kubernetes Pod Spec for Java Application

apiVersion: v1
kind: Pod
metadata:
  name: myapp
spec:
  containers:
    - name: myapp
      image: openjdk:17-slim
      resources:
        limits:
          memory: "512Mi"
          cpu: "500m"
        requests:
          memory: "256Mi"
          cpu: "100m"
      env:
        - name: JAVA_OPTS
          value: "-XX:+UseContainerSupport -XX:MaxRAMPercentage=50.0"
      # Or set explicit heap
      # - name: JAVA_OPTS
      #   value: "-Xmx256m"
      command: ["java", "-jar", "/app/myapp.jar"]

Observability Checklist

When running Java in containers in production, here is what to watch.

  • Monitor container memory usage vs container limit (should stay below 90% of limit)
  • Track JVM heap usage with jstat -gc or micrometer metrics
  • Monitor for exit code 137 (OOM kill) in container logs
  • Enable -Xlog:os+container=info in staging to verify container detection
  • Use NativeMemoryTracking to profile off-heap usage: -XX:NativeMemoryTracking=summary
  • Track Metaspace usage especially after class loading spikes
  • Monitor direct buffer usage: java.nio.ByteBuffer allocation counts
  • Compare JVM maxMemory() to container limit to verify awareness

Security Notes

Memory limits in containers provide a form of resource isolation, but they are not a security boundary. A container can exhaust the node’s memory if the kernel does not properly enforce cgroup limits across containers. Use proper node resource quotas and Kubernetes resource limits to prevent noisy-neighbor problems.

The -XX:+UseContainerSupport flag is enabled by default in many modern HotSpot builds on Linux, but availability and defaults depend on the vendor/update. It reads from the cgroup filesystem which is typically world-readable inside a container. There is no security implication to container awareness itself.

Be careful with -XX:MaxRAMPercentage in multi-tenant environments where container sizes vary. An attacker who can control the container size could potentially influence heap sizing in ways that affect application behavior.

Common Pitfalls / Anti-Patterns

Here are the most common mistakes when running Java in containers.

Running Java 8 in a container. Java 8 support depends on the vendor and update. Some builds backported container awareness; cgroup v2 support needs a later update than the first cgroup v1 support. Check the runtime release notes and verify the effective limit inside the container.

Ignoring off-heap memory. Setting -Xmx512m on a container with a 512MB limit means the total JVM memory usage can exceed 512MB. Always account for Metaspace, thread stacks, and direct buffers when sizing containers.

Setting memory limits equal to heap size. A common mistake is a container with 512MB limit and -Xmx512m. The JVM needs more memory than just the heap. Measure peak total process/container memory and leave headroom for non-heap allocations.

Assuming auto-detection works on all container runtimes. Some container runtimes (like older Docker versions or certain Kubernetes configurations) do not expose cgroup limits correctly. Always verify with -Xlog:os+container=info in staging.

Not handling OOM kills. When the container hits its memory limit, the OOM killer terminates the JVM process. If you do not have a process supervisor that restarts the container, your service goes down silently. Set up liveness probes in Kubernetes that detect process exits.

Quick Recap Checklist

Use this checklist when deploying Java applications to containers.

  • Verify the JDK vendor/update supports the cgroup version used by the host
  • Set container memory limit to at least 1.5x your expected heap size
  • Use -XX:MaxRAMPercentage rather than hardcoding -Xmx if you want fraction-based sizing
  • Account for Metaspace, thread stacks, and direct buffers in your memory budget
  • Enable -Xlog:os+container=info in staging to verify detection
  • Monitor container memory usage and track when it approaches the limit
  • Handle exit code 137 (OOM kill) with proper restart policies
  • Use NativeMemoryTracking if you suspect off-heap memory issues
  • Test with the same container limits in staging that you use in production
  • Set liveness probes that detect container failures from OOM kills

Interview Questions

1. How does the JVM detect container memory limits on Linux?

HotSpot reads the cgroup files exposed to the process when container support is available and enabled. File paths and supported controllers differ between cgroup v1 and v2. Check the JDK vendor/update and inspect the effective container limit; heap ergonomics are not a fixed fraction across every runtime.

2. Why did Java applications in containers often get OOM killed despite having a small heap?

Older or unsupported JVM builds may size themselves from host memory rather than the container limit. Some Java 8 vendor updates include backports, so check the exact JDK build and cgroup version. Additionally, even with correct heap sizing, off-heap memory usage (Metaspace, direct buffers, thread stacks, code cache) adds to total JVM memory consumption and can push the process over the container limit independently of heap size.

3. What is the relationship between container memory limit and heap size?

The heap ergonomics depend on the runtime build and flags; `-XX:MaxRAMPercentage` can set a configured fraction when container detection is working. However, the JVM uses memory beyond the heap for Metaspace (class metadata), thread stacks (1MB per thread), code cache (JIT compiled code), direct ByteBuffers (NIO), and internal JVM structures. Total process memory can exceed heap capacity substantially, depending on the workload and JVM configuration. For tight containers, set the limit to at least 1.5x your target heap size to account for this overhead.

4. How do you profile off-heap memory usage in a JVM running in a container?

Use the -XX:NativeMemoryTracking=summary JVM flag to enable native memory tracking, then run jcmd <pid> VM.native_memory summary to see a breakdown of off-heap usage including Metaspace, code cache, symbol tables, thread stacks, and internal JVM structures. For direct buffers, you can track allocation counts with -XX:MaxDirectMemorySize and monitoring via JMX. In Kubernetes, container metrics from cAdvisor or similar tools show total container memory usage, which is the most reliable signal for whether you are approaching the limit.

5. What happens when a container exceeds its memory limit?

When the total memory usage of all processes in a container exceeds the cgroup memory limit, the kernel first attempts to reclaim memory (if swap is available and configured). If reclaim is insufficient, the kernel OOM killer selects a process in the container to terminate. For a JVM, this is typically the JVM process itself, resulting in exit code 137 (128 + 9, where 9 is the signal number for SIGKILL). The container does not survive this; it either restarts (if managed by an orchestrator with a restart policy) or goes down. Unlike a JVM OOM which produces an exception within the JVM, an OOM kill is an OS-level termination that leaves no Java-level exception.

6. How does cgroup v2 differ from cgroup v1 in how the JVM reads memory limits?

cgroup v2 uses a unified hierarchy and different file paths than cgroup v1. For memory limits, cgroup v2 uses /sys/fs/cgroup/memory.max while cgroup v1 uses /sys/fs/cgroup/memory/memory.limit_in_bytes. For current usage, cgroup v2 uses /sys/fs/cgroup/memory.current while cgroup v1 uses /sys/fs/cgroup/memory/memory.usage_in_bytes. The JVM automatically detects which cgroup version is in use and reads the appropriate files. Some older distributions still use cgroup v1, and some environments may have a hybrid setup. Always verify with -Xlog:os+container=info which path the JVM is reading.

7. What is the relationship between -XX:MaxRAMPercentage and -XX:MaxRAM and which should you use?

MaxRAM sets an absolute ceiling on how much memory the JVM will use for heap and other internal structures combined. MaxRAMPercentage sets the heap as a percentage of the detected container memory limit (or physical memory if not in a container). MaxRAMPercentage is generally preferred because it scales with container sizes and produces more portable configurations. MaxRAM is useful when you need to set an absolute limit regardless of the container size. You cannot use both simultaneously—they are alternative ways to configure memory limits.

8. How does the JVM calculate the default heap size when running in a container with a memory limit?

There is no single default fraction that applies across JDK vendors, updates, flags, and container layouts. Check `MaxRAMPercentage`, `MaxHeapSize`, and the container log for the running image. An explicit `-Xmx` sets a heap ceiling, but it does not reserve memory for non-heap use.

9. What is NativeMemoryTracking and how do you use it to diagnose off-heap memory issues in containers?

NativeMemoryTracking (NMT) is a JVM feature that tracks internal memory usage beyond the Java heap. Enable it with -XX:NativeMemoryTracking=summary or detail. Use jcmd VM.native_memory summary to see a breakdown including: Java heap, Metaspace, code cache, thread stacks, internal structures, and symbol tables. NMT helps identify if off-heap memory is pushing you toward the container limit. Note that NMT itself has a small memory overhead (a few MB) and is intended for diagnostic use, not production continuous monitoring.

10. Why might a JVM with a small heap still get OOM killed in a container?

The heap is only part of total JVM memory usage. If Metaspace is growing (due to class loading), direct ByteBuffers are allocated, thread stacks consume space (1MB each), or the JIT compiler uses code cache, total memory can exceed the container limit even with a small heap. A 512MB container with -Xmx128m might still use 400-500MB total when accounting for Metaspace growth and direct buffers. Always monitor total container memory usage, not just heap usage. The JVM's maxMemory() only reports heap capacity, not actual memory consumption.

11. What is the effect of swap space on container memory limits and JVM behavior?

When a container reaches its memory limit and swap is available, the kernel attempts to reclaim memory by swapping out less-used pages. For the JVM, this causes severe performance degradation because Java heap access latency becomes unpredictable (pages may be swapped out). JVM processes are particularly vulnerable because they have large contiguous memory regions that the kernel may try to swap. It is generally recommended to set --memory-swap equal to --memory (disable swap for the container) to prevent swap thrashing. Alternatively, set swap to a small value and monitor for swap activity.

12. How does the JVM handle container memory limit detection on different operating systems?

Container awareness is primarily implemented for Linux cgroups (both v1 and v2). On macOS and Windows, the JVM runs in a virtualized environment and container limits are not exposed the same way. The JVM on macOS reports hardware memory (total RAM of the Mac) as container limits do not exist in the same way. In Docker Desktop on macOS, the JVM sees the host's total memory, not a container limit. This means applications developed on macOS may behave differently than in Linux containers. Always test container configurations in a Linux environment.

13. What is the relationship between heap sizing and garbage collector selection in containerized environments?

Garbage collectors have different native-memory and thread requirements, which vary with configuration and workload. Measure the selected collector under representative load; do not assume that changing collectors will reduce total container memory. Heap sizing still depends on the runtime flags and detected cgroup limit.

14. How does UseContainerSupport work and why might you need to disable it?

Many current HotSpot builds enable `UseContainerSupport` by default on Linux, but the supported cgroup versions and behavior depend on vendor and update. It causes the JVM to read cgroup memory limits and size the heap accordingly. You might disable it with -XX:-UseContainerSupport when you want the JVM to use physical memory instead of container limits (for example, if running on bare metal with a large memory footprint and container limits are incorrectly detected). Some container runtimes or orchestrator configurations expose incorrect cgroup values, causing wrong heap sizing, in which case disabling container support and using explicit -Xmx values is the workaround.

15. What is the difference between memory limit and memory request in Kubernetes and how does the JVM handle each?

Kubernetes memory limits are enforced by the cgroup system and represent the hard ceiling—exceeding this causes OOM kills. Memory requests are used by the scheduler to determine which node to place the pod on and do not affect cgroup limits. The JVM's container awareness reads the cgroup limit (Kubernetes memory.limit_in_bytes), not the request. If a container has a 512MB limit but only requests 256MB, the JVM sees 512MB and sizes the heap accordingly, regardless of the request. The request affects scheduling, not runtime behavior.

16. How do you calculate the appropriate container memory limit for a JVM application?

Measure peak container memory under representative load, including heap, Metaspace, thread stacks, direct buffers, code cache, JNI/native libraries, and agents. Use the container metrics for total usage and JVM tools for the heap and supported native-memory breakdowns. Add a margin for workload growth and test the limit before deployment; a fixed multiplier can be wrong in either direction.

17. What happens to the JVM's view of memory if the container's memory limit is changed dynamically (cgroup v2)?

The JVM reads the cgroup files once at startup and uses those values for the entire JVM lifetime. It does not dynamically re-read cgroup values if they change. If the container limit is modified while the JVM is running, the JVM continues using the originally detected limit. This is why restarting the JVM is sometimes necessary after container limit changes. Dynamic memory limit changes are not reflected in the JVM's behavior without a restart. For cgroup v1, the same behavior applies—the JVM takes a snapshot at startup.

18. Why might maxMemory() return a value that differs from what you expect based on container limits?

maxMemory() returns the maximum heap size the JVM will use, not the total memory available to the process. If UseContainerSupport is disabled or not working, it returns physical memory instead of container limits. If -Xmx is set explicitly, it returns that value. If the container limit is below the minimum heap the JVM calculates (16MB default), the calculation may produce unexpected results. Also, the JVM's internal rounding and calculation for MaxRAMPercentage may produce a maxMemory() slightly different from a simple calculation of container_limit × percentage.

19. How does container memory pressure affect JVM garbage collection behavior?

When the container is under memory pressure (approaching its limit), the OS may reclaim pages from the JVM process, causing GC to take longer because object access latency increases. If the container hits the limit, the OOM killer may terminate the JVM before GC can complete. The JVM has no direct awareness of container pressure—it only knows about heap usage. If the OS starts reclaiming memory aggressively, JVM performance degrades but the JVM does not have a mechanism to detect this specifically. Use container metrics to monitor this separately from JVM metrics.

20. What is the relationship between cgroup memory cpuset and memory localization and how does it affect JVM performance?

cpuset cgroups restrict which CPU cores a container can use and can also affect memory locality (NUMA). For JVM applications, memory locality matters for multi-threaded GC. If the container's cpuset spans multiple NUMA nodes, the JVM may have less efficient memory access patterns. The JVM does not automatically detect or adapt to cpuset constraints. For latency-sensitive applications on NUMA systems, consider binding the container to a single NUMA node using cpuset.cpus and cpuset.mems to ensure memory locality. This does not affect container awareness directly but impacts performance.

Reproducible Container Check

Run this with the same JDK image family and cgroup configuration you plan to deploy. It reports the container system information the JVM detects; compare that output with the limit set by Docker or Kubernetes. The exact diagnostic output varies by JDK update.

docker run --rm --memory=512m eclipse-temurin:21-jdk \
  java -XshowSettings:system -version

Then check the heap ergonomics separately:

docker run --rm --memory=512m eclipse-temurin:21-jdk \
  java -XX:+PrintFlagsFinal -version 2>&1 | grep -E "MaxHeapSize|MaxRAMPercentage|UseContainerSupport"

This is a diagnostic example, not a substitute for testing the production JDK vendor and update.

Further Reading

Conclusion

Container awareness has made running Java in Docker and Kubernetes significantly more manageable. Many current JVM builds can read Linux cgroup limits, but support depends on the JDK update and cgroup version. Detection does not size the entire process: native allocations, agents, buffers, stacks, and Metaspace also count against the container limit.

Monitor container memory alongside heap metrics, then repeat the check with the deployed JDK image after runtime or cgroup changes. When the default does not fit, set a measured heap cap or -XX:MaxRAMPercentage and confirm that non-heap usage still has room.

Category

Related Posts

CDS and AppCDS: Class Data Sharing for Faster JVM Startup

Learn how JVM Class Data Sharing works, create an AppCDS archive with Oracle JDK 21, and benchmark startup on your own workload.

#java #jvm #cds

JVM Bytecode Verification: Type Checking and Stack Map Frames

A practical guide to JVM bytecode verification by class-file version, including type inference, StackMapTable frames, VerifyError debugging, and verification limits.

#java #jvm #bytecode

Heap Walking and Allocation Tracking: TLABs and Analysis

Understand how the JVM allocates memory with TLABs, how to track allocations with low overhead, and how heap walking tools analyze object graphs.

#jvm #heap #tlab