package dev.elaine.jvmlab;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Deque;

public final class GcPressureSample {
    private GcPressureSample() {
    }

    public static void main(String[] args) {
        int seconds = args.length == 0 ? 10 : Integer.parseInt(args[0]);
        Instant deadline = Instant.now().plus(Duration.ofSeconds(seconds));
        Deque<byte[]> survivors = new ArrayDeque<>();
        long allocatedBytes = 0;

        while (Instant.now().isBefore(deadline)) {
            byte[] block = new byte[256 * 1024];
            allocatedBytes += block.length;
            if ((allocatedBytes / block.length) % 16 == 0) {
                survivors.addLast(block);
            }
            if (survivors.size() > 64) {
                survivors.removeFirst();
            }
        }
        System.out.printf("累计分配 %.1f MiB，存活块 %d%n", allocatedBytes / 1024.0 / 1024.0, survivors.size());
    }
}
