Performance
performance1GcAllocationDemo
- Path
- pkg19performance/performance1GcAllocationDemo.java
- Package
- pkg19performance
- Study order
- 1
- Run
- Single-file source launch
- Command
- java pkg19performance/performance1GcAllocationDemo.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg19performance;2 3/*4 * performance1GcAllocationDemo.java5 * ---------------------------------6 * Allocation pressure and GC: observe how object churn triggers collection.7 *8 * DEFINITION:9 * Short-lived objects live in Eden; minor GC clears them. Promoted long-lived10 * objects fill Old gen and trigger major GC. Excessive allocation = GC overhead.11 *12 * KEY POINTS:13 * - Prefer object reuse, pools, and primitives where hot.14 * - -Xlog:gc* logs GC events (Java 9+ unified logging).15 * - Run with: java -Xlog:gc:stdout performance1GcAllocationDemo.java16 */17public class performance1GcAllocationDemo {18 19 public static void main(String[] args) {20 System.out.println("Allocating 500k short-lived objects...");21 long before = System.nanoTime();22 for (int round = 0; round < 5; round++) {23 Object[] junk = new Object[100_000];24 for (int i = 0; i < junk.length; i++) junk[i] = new byte[64];25 }26 long ms = (System.nanoTime() - before) / 1_000_000;27 System.out.println("Done in " + ms + " ms");28 29 long heapUsed = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024;30 System.out.println("Heap used (approx): " + heapUsed + " KB");31 System.out.println("\nTip: rerun with -Xlog:gc:stdout to see GC activity");32 }33}