package ex7;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

public final class Profiler {

    private static final Map<MonitorEntry, LongAdder> monitorToAccessCount = new ConcurrentHashMap<>();

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            for (final var entry : monitorToAccessCount.entrySet()) {
                System.out.printf("%d - %s - #Locks: %d%n",
                        entry.getKey().monitorHashCode(),
                        entry.getKey().name(),
                        entry.getValue().intValue()
                );
            }
        }));
    }

    private Profiler() {
    }


    public static void countMonitorAccess(final Object obj) {
        final MonitorEntry monitorEntry = new MonitorEntry(obj.hashCode(), obj.getClass().getName());
        monitorToAccessCount.computeIfAbsent(monitorEntry, k -> new LongAdder()).increment();
    }


}
