Lesson · Packaging, Deployment & Runtime Tuning
Packaging, deployment and runtime tuning
13 min readPackaging, Deployment & Runtime Tuning
A jar is a zip with a manifest; everything after that is a ladder from plain jar to shaded jar, jlink image, installer and native binary. This lesson climbs it, then covers the container and flag decisions that decide whether the process survives production.
The jar, in three lines
A jar is a zip file with a manifest. The manifest lives at META-INF/MANIFEST.MF, and one line in it turns a library into a program: Main-Class: com.acme.ledger.Main is what java -jar ledger.jar reads to know where to start. The format and the jar command itself belong to tools-early; what matters here is that everything later in this lesson is still that zip, with more inside it.
Three consequences follow from the format. Dependencies are not inside a plain jar, so they must sit on the classpath or be named by a manifest Class-Path. Resources are ordinary entries, so a missing resource is a packaging question, not a classloading mystery. And the manifest is the only metadata the launcher honours, which is why build tools write it for you rather than asking you to zip by hand.
A jar is a shipping container, not a program. The runtime, the dependencies and the manifest are what turn it into one.
The packaging ladder
Packaging options form a ladder. Each rung bundles more of the environment into the artifact, and each rung charges you in build complexity. Climb only as far as the deployment actually requires.
| Rung | What ships | What it needs |
|---|---|---|
| plain jar | your classes and resources | a JVM on the host and the dependencies on the classpath |
| fat / shaded jar | your classes plus every dependency in one file | a shade plugin that merges and relocates resources |
| jlink image | a trimmed runtime plus your modules | a modular build, so module-info or explicit add-modules |
| jpackage installer | a native installer with a runtime inside | JDK 14 or newer, plus a runtime or image to bundle |
| native image | one ahead-of-time compiled executable | a closed-world build with reachability metadata |
The ladder trades build complexity for runtime guarantees. A fat jar trades nothing and controls nothing; a native image controls everything and costs the most to build.
Packaging · one jar, four verdicts
each rung bundles more of the environment
your classes plus every dependency in one archive
trade: big file, and resource merging to get right
a trimmed runtime plus your modules
trade: a module list to maintain as the build input
everything, compiled ahead of time
trade: a closed world, so reflection needs configuration
a runtime plus a native installer
trade: one installer per platform to build and sign
decision strip · startup budget against image size
startup relaxed · size: not the constraint
plain or fat jar on the host runtime
startup relaxed · size: small image matters
jlink image, trimmed runtime
startup tight · size: not the constraint
jlink image plus a CDS archive
startup tight · size: small image matters
native image
CDS is the cheap middle: a default archive has shipped with the JDK since JDK 12, and dynamic archiving since JDK 13 records application classes after one run. The right-hand column is the one that needs reflection configuration at build time.
Fat jars: shading, relocation and the services trap
A fat jar, also called an uber or shaded jar, unpacks every dependency and writes all of it into one archive. It solves the classpath problem completely: one file, java -jar, done. In Maven the tool is maven-shade-plugin; Gradle has the shadow plugin with the same idea.
Two things go wrong. First, two dependencies can ship a file at the same path, and the merge has to be deliberate rather than first-one-wins. Second, and worse, multi-release jars and service files need special handling: ServiceLoader reads provider lists from META-INF/services, and the contract there (service-loading covers the mechanism) is that every provider file at the same path must be merged, not overwritten, or one provider silently disappears from the shaded jar. The shade plugin has a resource transformer for exactly this, and relocation (relocation rules that rewrite package names) is the other common requirement when two versions of a library must coexist inside one artifact.
- Check what the merge kept. An overwritten service file or a dropped license file is invisible until the provider is missing at run time.
- Relocate only when you must. Rewriting packages is powerful and fragile; it is for the case where two library versions genuinely must ship together.
- Signature files break. Strip
META-INF/*.SFand*.DSAfrom dependencies during shading, or the JVM rejects the merged archive as tampered with.
A fat jar is a merge, and merges lose data. Diff the archive contents against the dependency list once, and keep the transformer configuration in version control.
jlink images and jpackage installers
jlink builds a custom runtime image: you name the modules you need, and it assembles a directory containing a trimmed JVM plus your code. jlink --add-modules java.base --output runtime produces the smallest possible runtime. The input side is the module system, which modules covers in depth; from the packaging side, the payoff is a runtime you control, usually far smaller than a full JDK, with no dependency on whatever the host has installed.
jpackage (JDK 14 and later) goes one step further and produces a native installer or an app image with that runtime bundled inside: msi on Windows, deb and rpm on Linux, dmg and pkg on macOS. The result is a program a user installs like any other, which is the desktop answer to "Java is not installed".
- jlink needs modules. A non-modular jar can still be linked by naming automatic modules, but the clean result comes from a modular build.
- jpackage needs a runtime to bundle: a jlink image, or it will jlink one for you.
- Both are part of the build, not a manual step: run them in the pipeline so the image is rebuilt whenever the code is.
Bundle the runtime when the host is not yours. A jlink image or an installer removes the question of which Java is installed.
Startup: CDS and the native image trade
Startup cost is class loading, verification and JIT warm-up. Class data sharing attacks the first two, by mapping a pre-parsed archive of core classes instead of re-reading and re-verifying them. A default CDS archive has shipped with the JDK since JDK 12 (JEP 341), holding about 1300 core library classes, and the JVM uses it automatically with -Xshare:auto, the default. For application classes, dynamic archiving since JDK 13 adds one step: run once with -XX:ArchiveClassesAtExit=app.jsa, then start with -XX:SharedArchiveFile=app.jsa and the archive is mapped instead of rebuilt.
A GraalVM native image takes the opposite approach: compile the closed world ahead of time into a single executable. Startup drops to tens of milliseconds and memory drops with it, because there is no JIT compiler to warm up. The price is a build where everything reachable must be known: reflection needs configuration, provided by reachability metadata or a tracing agent, which reflection-in-frameworks covers. Peak throughput can also be lower than a warmed JVM, so the honest comparison is startup against steady state, both measured.
CDS is a cheap win on any JVM; a native image is a different runtime. Measure both against the workload, and remember that warm-up is a cost the native image never pays.
Containers: limits, images and the heap
A JVM in a container respects the container's memory limit. Container awareness has been on by default since JDK 10 through UseContainerSupport, so the heap is sized from the cgroup limit rather than from the host's physical memory. -XX:MaxRAMPercentage says what fraction of that limit the heap may use; its default is 25 percent.
That default exists because the heap is not the whole process: metaspace, code cache, thread stacks and direct buffers live outside it. A service with a 1 GB limit therefore gets a 256 MB default heap, and raising the percentage to 75 is a common, deliberate choice once the other regions are accounted for.
On the image side, three habits keep containers small: start from a maintained base such as Eclipse Temurin, use a multi-stage build so the JDK and the sources do not ship in the runtime image, and consider a distroless runtime when you want no shell and no package manager in the final layer. Nothing in the image should need to change when the container is rescheduled, which is where configuration comes in.
- Never hardcode -Xmx in a container manifest. The limit is a deployment decision and changes between environments; a fixed heap does not.
- One process per container, and let the JVM handle SIGTERM: shutdown hooks run, in-flight work finishes, and the orchestrator's grace period is respected.
- Rebuild the image on every change. A jar copied in by hand is a deployment that nobody can reproduce.
The JVM reads the cgroup, so the manifest should not fight it. Express the heap as a percentage of the limit and let the deployment own the limit.
The production flags worth knowing
Most JVM flags should stay unset. These are the ones that earn their place in a start script.
- `-Xms` equal to `-Xmx` on a server. A fixed heap avoids resize work at run time, and the JVM man page notes that server deployments commonly set both to the same value. It is a bargain you make with container memory: reserve exactly what you will use.
- One GC choice, matched to the budget. G1 is the default and usually the right answer; gc-collectors covers choosing between it and the low-latency collectors.
- Heap dump on OOM:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps. The dump is the difference between diagnosing the leak and guessing at it; the tools for reading it are documented in jvm-tooling. - Unified logging to a file:
-Xlog:gc*:file=/var/log/app-gc.log:filecount=5,filesize=10M, available since JDK 9 (JEP 158). One line gives you rotating GC history, and GC log analysis is where pause questions get answered. - `-XX:+ExitOnOutOfMemoryError` terminates on the first OOM instead of limping. Pair it with dump-on-OOM, and let the orchestrator restart into a known state rather than serving errors.
Every flag is a decision to maintain. Add one only when it fixes a problem you have measured.
Deployment models and configuration
The packaging choice and the deployment target decide each other. A long-running service on a VM or in a pod is best served by a jar and a JVM that optimises itself; a function that scales to zero is where a native image pays for its build complexity. Serverless turns startup into a per-request cost, so cold start behaviour matters more than steady state.
| Target | Startup | Steady state | Strengths |
|---|---|---|---|
| jar on a VM | JVM boot plus warm-up | full JIT, familiar operations | simplest to operate when you own the host |
| container | image pull plus JVM boot | full JIT, one image per service | the default for microservices and orchestration |
| native image | tens of milliseconds | no warm-up, usually lower peak | scale-to-zero and latency-sensitive small services |
| serverless function | cold start dominates the tail | paid per invocation | spiky traffic and event handlers |
- Configuration comes from the environment, the twelve-factor rule: ports, credentials and database URLs are read from variables, never baked into the jar, so the same artifact runs in every environment.
- Secrets stay out of the image and out of the jar. A secret in a layer is a secret in a registry and in every cache that touched it.
- Deployment is reproducible or it is folklore: build the artifact once, promote that artifact through environments, and never rebuild between them.
The artifact should be environment-agnostic; only the environment is not. If two environments need two builds, the build is doing configuration work.
Packaging lab · target meets artifact
authored verdicts, no benchmarkswhere it runs
the pod spec owns the memory limit, and the image is the deployment unit
what ships
one file, dependencies inside, runtime from the host
Image equals JRE plus jar, limits come from the pod spec, and the heap follows the limit. It is the shape every operator already knows.
Verifying a deployment
A deployment deserves three checks before anyone trusts it. They take a minute and they close the gap between what you built and what is actually running.
java -versionfrom inside the container or service, to see the exact runtime build that is live.- A hash comparison between the deployed jar and the one CI produced (sha256sum), so a rebuilt or hand-modified artifact cannot masquerade as the tested one.
- A smoke test that touches one real dependency, such as opening a database connection, because a process that starts is not a process that works.
Trust the artifact you tested, not the one you rebuilt. Hashing the jar is how that becomes a fact.
What to keep
Package only as far up the ladder as the target needs, keep the artifact environment-agnostic, let the container limit drive the heap, and add flags one at a time, each because it answered a measured question. Packaging decides what runs; the runtime flags decide how long it runs well.
Packaging decides what runs; runtime flags decide whether it survives production.
The -Xmx that capped the wrong thing
The container gets a 2 GB limit, and the start script says -Xmx512m because that is what worked on a smaller machine. The JVM now OOMs while the node still has 1.5 GB free, and everyone blames a memory leak that does not exist. The heap must be a percentage of the limit, not a number that predates it: -XX:MaxRAMPercentage=75, with the limit owned by the deployment manifest. Container awareness has sized the heap from the cgroup since JDK 10, so a hardcoded -Xmx is the one number guaranteed to be wrong somewhere.
Interview angles
Fat jar or jlink image?+
Fat jar when the host provides a JVM and you want the simplest artifact: one file, every dependency, java -jar. A jlink image when you want to control the runtime itself, usually to shrink it and pin its version, which needs a modular build. The choice is really about who owns the runtime: the platform, or the artifact.
How does shading break ServiceLoader, and what is the fix?+
ServiceLoader reads provider lists from META-INF/services. When several dependencies contribute a file at the same path, a naive merge overwrites one with the other, and the missing provider is invisible until that code path runs. The shade plugin ships a resource transformer that merges service files instead of replacing them; relocation rules can also rewrite the provider lines, so the merge has to happen with relocation in mind.
Follow-up: What else gets lost in the merge? Signature files such as META-INF/*.SF must be stripped, or the merged jar looks tampered with, and duplicate license files show the same overwrite behaviour.
Why is a hardcoded -Xmx in a container dangerous?+
The container limit is a deployment detail, and a heap fixed below it makes the JVM fail while memory is still available. Since JDK 10 the JVM reads the cgroup limit itself through container support, so the heap should be expressed as -XX:MaxRAMPercentage (default 25 percent of the limit), with the deployment owning the limit.
Common misconception: That the JVM sees the host's memory inside a container and needs a fixed heap to stay polite. It has read the container limit by default for years; the fixed value is the problem, not the safety measure.
What does a native image trade away?+
Build flexibility and sometimes peak throughput. Startup and memory win because there is no JIT to warm up, but the image is built for a closed world, so reflective access needs explicit configuration, and the fully optimised peak of a warmed JVM can be higher. Choose it for scale-to-zero and start-up-sensitive services, not as a universal upgrade.
The comparison to make is honest on both axes: startup measured against the cold JVM, and throughput measured after warm-up against the native binary. A native image that starts in 30 ms and peaks 10 percent lower is a bargain for a function and a loss for a long-lived batch worker.