Limiting java application's memory and cpu usage

you can limit memory usage by -Xmx option and you can limit CPU usage by setting priority of the process and/or CPU affinity.


The JVM has no control over CPU usage nor priority.

JVM has control over max/min Memory usage.

There is a workaround. It is possible to run each JVM in a separate [Docker container][1]. And control the resource (Memory, CPU, Network, IO) allocation for each container. That is exactly the added value of the Docker containers.

[1]: The JVM has no control over CPU usage nor priority. Yet you can run each JVM in a separate Docker container. And control the resource allocation foreach container. That is exactly the added value of the Docker containers.


Docker offers up resource management options for limiting the cpu access for running docker containers. Have a look at the CFS scheduler options available with docker run from Limit a container's resources in the Docker documentation, such as:

  • --cpus=<value> - Specify how much of the available CPU resources a container can use. For instance, if the host machine has two CPUs and you set --cpus="1.5", the container is guaranteed at most one and a half of the CPUs. This is the equivalent of setting --cpu-period="100000" and --cpu-quota="150000". Available in Docker 1.13 and higher.
  • --cpuset-cpus - Limit the specific CPUs or cores a container can use. A comma-separated list or hyphen-separated range of CPUs a container can use, if you have more than one CPU. The first CPU is numbered 0. A valid value might be 0-3 (to use the first, second, third, and fourth CPU) or 1,3 (to use the second and fourth CPU).

These options are also available via docker-compose, when deploying a Docker swarm / stack, as mentioned in Compose file version 3 reference under resources:

version: '3'
services:
  redis:
    image: redis:alpine
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 50M
        reservations:
          cpus: '0.25'
          memory: 20M```

Note: that the legacy resource options in docker compose v2 are now limited to stacks in the migration to v3.