Video in progress

How do Transparent Huge Pages on Linux relate to the JVM's large pages setting, and why does THP sometimes worsen latency?

Large pages reduce TLB misses and speed up an application with a big heap. But in always mode THP makes the kernel merge and defragment pages in the background, which causes unexpected stalls. For the JVM, the madvise mode with -XX:+UseTransparentHugePages is safer.

📖 Answer

The usual page is 4 KB. For a 32 GB heap that is millions of pages, and the TLB (the address translation cache) is always short. 2 MB pages cut this number by a factor of 512 and give a few percent, sometimes more, in applications that access a lot of memory (the GC does too).

There are two mechanisms:

  • Static huge pages (hugetlbfs): preallocated, -XX:+UseLargePages. Stable, but needs administration and the memory is reserved just for this purpose.
  • THP: the kernel merges pages automatically. The modes: always, madvise, never.

The problem with always: khugepaged gathers pages in the background, and when memory is fragmented the kernel may do compaction directly, which holds up allocation for milliseconds. That is why some databases recommend turning THP off.

This is the setting I recommend for the JVM:

cat /sys/kernel/mm/transparent_hugepage/enabled    # should be [madvise]
java -XX:+UseTransparentHugePages -Xms16g -Xmx16g -XX:+AlwaysPreTouch -jar app.jar

In madvise mode only an application that asks gets large pages, and the JVM asks for the heap.

In a container this is a node-level setting, so you have to agree it with the platform team. And as always, measure the result: in a service with a small heap (1-2 GB) the benefit is barely noticeable, while in a service with a big heap that is heavy on GC it can be significant.