Add gc-basics: Java garbage collection explained and measured on JDK 25, 27, 28 EA
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b44MquEzmd9QMkZCd7
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
f7b6c1efca
commit
876ae1bb5c
@@ -0,0 +1,93 @@
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* A synthetic service: a live set that stays in memory plus a steady stream of short-lived garbage.
|
||||
* A "ticker" thread asks to sleep 1 ms in a loop and records how late it wakes up; a stop-the-world pause shows up as lateness.
|
||||
* Usage: Churn <liveMB> <seconds> [flat|graph] [wait]
|
||||
* flat (default): the live set is one big list of 1 KB byte arrays: cheap for a collector to copy, no pointers inside.
|
||||
* graph: the live set is a HashMap of small entries that are replaced all the time: many objects, many old-to-young pointers.
|
||||
* wait: parks the JVM at the end so jcmd can look at it.
|
||||
*/
|
||||
public class Churn {
|
||||
static volatile boolean stop;
|
||||
static long maxStallNs, over10ms, over50ms;
|
||||
|
||||
static final List<byte[]> live = new ArrayList<>();
|
||||
static final java.util.HashMap<Integer, byte[]> graph = new java.util.HashMap<>(); // "graph" mode: many small linked objects, mutated often
|
||||
static boolean graphMode;
|
||||
static int graphKeys;
|
||||
static final byte[][] ring = new byte[16384][]; // recent "requests" stay reachable briefly, so the JIT cannot optimise the allocations away
|
||||
static int slot;
|
||||
static long allocatedBytes, ops;
|
||||
|
||||
/** Runs the request loop for the given time. */
|
||||
static void serve(long nanos) {
|
||||
var rnd = ThreadLocalRandom.current();
|
||||
long end = System.nanoTime() + nanos;
|
||||
allocatedBytes = 0;
|
||||
ops = 0;
|
||||
while (System.nanoTime() < end) {
|
||||
// short-lived garbage: a few small arrays per "request"
|
||||
for (int k = 0; k < 8; k++) {
|
||||
byte[] b = new byte[256 + rnd.nextInt(768)];
|
||||
ring[slot] = b;
|
||||
slot = (slot + 1) & (ring.length - 1);
|
||||
allocatedBytes += b.length;
|
||||
}
|
||||
// some requests replace one piece of the live set, so some objects live a while and then die
|
||||
if (graphMode) { if ((ops & 1) == 0) graph.put(rnd.nextInt(graphKeys), new byte[48]); }
|
||||
else if (ops % 200 == 0) live.set(rnd.nextInt(live.size()), new byte[1024]);
|
||||
ops++;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
int liveMb = Integer.parseInt(args[0]);
|
||||
int seconds = Integer.parseInt(args[1]);
|
||||
graphMode = args.length > 2 && args[2].equals("graph");
|
||||
boolean waitForJcmd = args.length > 3 && args[3].equals("wait");
|
||||
|
||||
if (graphMode) {
|
||||
graphKeys = liveMb * 1024 * 1024 / 120; // roughly 120 bytes per entry: HashMap node + Integer key + 48-byte array
|
||||
for (int i = 0; i < graphKeys; i++) graph.put(i, new byte[48]);
|
||||
} else {
|
||||
for (int i = 0; i < liveMb * 1024; i++) live.add(new byte[1024]); // the live set: 1 KB chunks reachable for the whole run
|
||||
}
|
||||
|
||||
// Warm-up: let the JIT compile the loop and let the collector move the freshly built live set out of the young
|
||||
// generation. Only after that does the ticker start, so a one-off startup pause is not mistaken for steady state.
|
||||
serve(1_500_000_000L);
|
||||
|
||||
Thread ticker = new Thread(() -> {
|
||||
long prev = System.nanoTime();
|
||||
while (!stop) {
|
||||
try { Thread.sleep(1); } catch (InterruptedException e) { return; }
|
||||
long now = System.nanoTime();
|
||||
long late = now - prev - 1_000_000L;
|
||||
if (late > maxStallNs) maxStallNs = late;
|
||||
if (late > 10_000_000L) over10ms++;
|
||||
if (late > 50_000_000L) over50ms++;
|
||||
prev = now;
|
||||
}
|
||||
});
|
||||
ticker.setDaemon(true);
|
||||
ticker.start();
|
||||
|
||||
serve(seconds * 1_000_000_000L);
|
||||
|
||||
if (waitForJcmd) { System.out.println("READY"); System.out.flush(); Thread.sleep(4000); }
|
||||
stop = true;
|
||||
Thread.sleep(5);
|
||||
|
||||
StringBuilder names = new StringBuilder();
|
||||
for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) names.append(b.getName()).append(" ");
|
||||
System.out.printf("collector beans : %s%n", names.toString().trim());
|
||||
System.out.printf("live set : %d MB (%s), heap max %d MB%n", liveMb, graphMode ? "graph" : "flat", Runtime.getRuntime().maxMemory() >> 20);
|
||||
System.out.printf("requests : %d (%.0f MB allocated)%n", ops, allocatedBytes / 1048576.0);
|
||||
System.out.printf("ticker max stall: %.1f ms; wakeups >10 ms: %d; >50 ms: %d%n", maxStallNs / 1e6, over10ms, over50ms);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** What finalize() does today. Compile with -Xlint:deprecation to see the compiler's view of it. */
|
||||
public class Finalize {
|
||||
static class Holder {
|
||||
@SuppressWarnings({"removal", "deprecation"})
|
||||
@Override
|
||||
protected void finalize() {
|
||||
System.out.println("finalize() ran");
|
||||
}
|
||||
}
|
||||
|
||||
static class Holder2 {
|
||||
@Override
|
||||
protected void finalize() { // deliberately not suppressed: javac prints a removal warning
|
||||
System.out.println("finalize() ran");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new Holder();
|
||||
System.gc();
|
||||
Thread.sleep(500);
|
||||
System.out.println("main done");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** A classic leak: a static collection that only ever grows. Argument "big" keeps 1 MB arrays, "small" keeps tiny objects. */
|
||||
public class Leak {
|
||||
static final List<Object> CACHE = new ArrayList<>(); // a GC root: nothing ever removes from it
|
||||
|
||||
public static void main(String[] args) {
|
||||
boolean big = args.length > 0 && args[0].equals("big");
|
||||
long n = 0;
|
||||
try {
|
||||
while (true) {
|
||||
CACHE.add(big ? new byte[1 << 20] : new int[8]);
|
||||
n++;
|
||||
}
|
||||
} catch (OutOfMemoryError e) {
|
||||
int kept = CACHE.size();
|
||||
CACHE.clear(); // give the JVM room to print
|
||||
System.out.println("kept " + kept + (big ? " arrays of 1 MB" : " tiny objects") + " then: java.lang.OutOfMemoryError: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
/**
|
||||
* Reachability, observed. A WeakReference does not keep its target alive, so after a full collection
|
||||
* "get() == null" means "the collector found it unreachable from the roots".
|
||||
*/
|
||||
public class Reach {
|
||||
static class MyObject {
|
||||
final String name;
|
||||
MyObject child;
|
||||
MyObject(String name) { this.name = name; }
|
||||
}
|
||||
|
||||
public static MyObject staticObj; // a GC root: a static field
|
||||
|
||||
static WeakReference<MyObject> weak(MyObject o) { return new WeakReference<>(o); }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
MyObject localObj = new MyObject("A"); // a GC root: a local variable
|
||||
staticObj = new MyObject("B");
|
||||
localObj.child = new MyObject("C"); // 'C' is reachable from 'A'
|
||||
MyObject unreachable = new MyObject("D"); // referenced by nothing once we drop the variable
|
||||
|
||||
// An "island": two objects that point at each other, with no path from any root.
|
||||
MyObject x = new MyObject("X");
|
||||
MyObject y = new MyObject("Y");
|
||||
x.child = y;
|
||||
y.child = x;
|
||||
|
||||
var refs = new WeakReference[] { weak(localObj), weak(staticObj), weak(localObj.child), weak(unreachable), weak(x), weak(y) };
|
||||
String[] names = { "A (local variable)", "B (static field)", "C (child of A)", "D (no references)", "X (cycle with Y, no root)", "Y (cycle with X, no root)" };
|
||||
|
||||
unreachable = null;
|
||||
x = null;
|
||||
y = null;
|
||||
|
||||
System.gc(); // for the demonstration only; see "Forget System.gc() exists" in the article
|
||||
|
||||
for (int i = 0; i < refs.length; i++) {
|
||||
System.out.printf("%-28s %s%n", names[i], refs[i].get() != null ? "alive" : "collected");
|
||||
}
|
||||
System.out.println("A and C are still used here: " + localObj.name + " -> " + localObj.child.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/** The stack-versus-heap snippet from the article: what lives where, and when it goes away. */
|
||||
public class StackAndHeap {
|
||||
public void myMethod() {
|
||||
int localValue = 10; // stored directly on the stack for this method's frame
|
||||
String message = "Hello"; // the *reference* 'message' is on the stack...
|
||||
// ...but the String object itself is on the heap (a literal lives in the string pool, also on the heap).
|
||||
System.out.println(localValue + " " + message);
|
||||
} // the frame is popped here; 'localValue' and 'message' (the reference) are gone
|
||||
|
||||
public static void main(String[] args) {
|
||||
new StackAndHeap().myMethod();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** What one System.gc() call costs when the heap holds a real live set. */
|
||||
public class SysGc {
|
||||
public static void main(String[] args) {
|
||||
List<byte[]> live = new ArrayList<>();
|
||||
for (int i = 0; i < 150 * 1024; i++) live.add(new byte[1024]); // 150 MB that must be kept
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
long t = System.nanoTime();
|
||||
System.gc();
|
||||
System.out.printf("System.gc() #%d took %.1f ms%n", i, (System.nanoTime() - t) / 1e6);
|
||||
}
|
||||
System.out.println("live chunks still referenced: " + live.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** The deterministic way to release a file handle: try-with-resources, not finalize(). */
|
||||
public class TryWithResources {
|
||||
public static void main(String[] args) throws IOException {
|
||||
Path file = Files.createTempFile("gc-basics", ".txt");
|
||||
Files.writeString(file, "hello");
|
||||
try (FileInputStream fis = new FileInputStream(file.toFile())) {
|
||||
System.out.println("read byte count: " + fis.readAllBytes().length);
|
||||
} catch (IOException e) {
|
||||
System.out.println("handle exception here: " + e);
|
||||
} // fis.close() has already run here, whether or not an exception was thrown
|
||||
System.out.println("stream closed deterministically at the end of the try block");
|
||||
Files.delete(file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Prints which collector this JVM actually picked, taken from the JVM itself rather than from a flag listing. */
|
||||
public class Which {
|
||||
public static void main(String[] args) {
|
||||
var beans = ManagementFactory.getGarbageCollectorMXBeans();
|
||||
System.out.println("processors seen by JVM : " + Runtime.getRuntime().availableProcessors());
|
||||
System.out.println("max heap : " + Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
|
||||
System.out.println("collector MXBeans : " + beans.stream().map(b -> b.getName()).collect(Collectors.joining(" | ")));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user