|
1 | 1 | package jvm.oom; |
2 | 2 |
|
| 3 | +import jvm.MallocBench; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | + |
| 6 | +import java.nio.ByteBuffer; |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | +import java.util.concurrent.ExecutorService; |
| 10 | +import java.util.concurrent.Executors; |
| 11 | +import java.util.concurrent.ThreadLocalRandom; |
| 12 | +import java.util.concurrent.TimeUnit; |
| 13 | + |
3 | 14 | /** |
4 | 15 | * https://github.com/Kuangcp/Note/blob/master/Linux/Base/LinuxBase.md#glibc-ptmalloc2 |
5 | 16 | * |
6 | 17 | * @author Kuangcp |
7 | 18 | * 2025-05-15 21:59 |
| 19 | + * @see MallocBench |
8 | 20 | */ |
| 21 | +@Slf4j |
9 | 22 | public class DirectMemoryGlibcGrow { |
10 | 23 | //TODO 模拟出Glibc thread arena 占用大的情况 |
11 | 24 | //TODO 替换 jemalloc 后查看是否有问题 |
| 25 | + |
| 26 | + |
| 27 | + // https://medium.com/@daniyal.hass/how-glibc-memory-handling-affects-java-applications-the-hidden-cost-of-fragmentation-8e666ee6e000 |
| 28 | + public static void fragment() throws InterruptedException { |
| 29 | + List<ByteBuffer> buffers = new ArrayList<>(); |
| 30 | + // Allocate large buffers and release them to see memory impact |
| 31 | + for (int i = 0; i < 50; i++) { |
| 32 | + int delta = ThreadLocalRandom.current().nextInt(100) + 33; |
| 33 | + System.out.print(delta + ", "); |
| 34 | + buffers.add(ByteBuffer.allocateDirect(delta * 1024 * 1024)); // 100 MB each |
| 35 | + |
| 36 | + buffers.remove(0); |
| 37 | +// if (i % 2 == 0) buffers.remove(0); // Simulate variable memory usage |
| 38 | + } |
| 39 | + |
| 40 | + System.out.println("Memory allocations complete. Check OS memory usage."); |
| 41 | + } |
| 42 | + |
| 43 | + public static void loopFragment() throws InterruptedException { |
| 44 | + TimeUnit.SECONDS.sleep(10); |
| 45 | + ExecutorService xo = Executors.newFixedThreadPool(3); |
| 46 | + Runnable run = () -> { |
| 47 | + try { |
| 48 | + for (int i = 0; i < 1000; i++) { |
| 49 | + TimeUnit.SECONDS.sleep(3); |
| 50 | + fragment(); |
| 51 | + System.out.println("loop " + i); |
| 52 | + } |
| 53 | + } catch (Exception e) { |
| 54 | + log.error("", e); |
| 55 | + } |
| 56 | + }; |
| 57 | + xo.submit(run); |
| 58 | + xo.submit(run); |
| 59 | + |
| 60 | + } |
| 61 | + |
12 | 62 | } |
0 commit comments