package com.ankurm.hibernatedemo.hikari; import static org.assertj.core.api.Assertions.assertThat; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /** * The original article's "leak detection" advice was a single line -- "set * leakDetectionThreshold to catch connections that are opened but never closed" -- with no * mention of a floor value. Measuring it surfaces a trap the article missed entirely: HikariCP * silently disables leak detection for any threshold under 2000ms, rather than honoring a short * value for a fast test or a tight dev-loop check. * *

Both behaviors are confirmed by disassembling {@code HikariConfig.class} in {@code * HikariCP-7.0.2.jar}: {@code validate()} logs {@code "{} - leakDetectionThreshold is less than * 2000ms or more than maxLifetime, disabling it."} via {@code HikariConfig}'s own logger and * resets the field to {@code 0} (disabled) whenever the configured value is under 2000ms -- this * runs synchronously inside the {@code HikariDataSource} constructor, before any connection is * ever checked out. * *

Docs: docs/19-hikaricp-connection-pooling.md */ class HikariLeakDetectionTest { private HikariDataSource dataSource; @AfterEach void tearDown() { if (dataSource != null) { dataSource.close(); } } @Test void thresholdUnder2000ms_isSilentlyDisabled_notShortenedToWhatWasAsked() { Logger configLogger = (Logger) LoggerFactory.getLogger(HikariConfig.class); ListAppender appender = new ListAppender<>(); appender.start(); configLogger.addAppender(appender); HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:h2:mem:hikarileakshort;DB_CLOSE_DELAY=-1"); config.setUsername("sa"); config.setLeakDetectionThreshold(500); // the trap: under the 2000ms floor dataSource = new HikariDataSource(config); // validate() runs here, synchronously System.out.println("RESULT[hikari-leak-threshold-floor]: requested leakDetectionThreshold=500ms | " + "actual leakDetectionThreshold after construction=" + config.getLeakDetectionThreshold() + "ms | logged warnings=" + appender.list.size() + (appender.list.isEmpty() ? "" : " | message=" + appender.list.get(0).getFormattedMessage()) + " -- HikariCP does not clamp 500ms up to 2000ms, it disables leak detection " + "entirely and logs a WARN naming the reason."); assertThat(config.getLeakDetectionThreshold()) .as("HikariConfig.validate() resets a sub-2000ms threshold to 0 (disabled), it does " + "not round it up to the 2000ms floor") .isZero(); assertThat(appender.list) .as("and it says so, once, at construction time") .hasSize(1); assertThat(appender.list.get(0).getFormattedMessage()) .contains("leakDetectionThreshold is less than 2000ms"); configLogger.detachAppender(appender); } @Test void thresholdAtOrAbove2000ms_actuallyLogsAWarning_whenAConnectionIsHeldPastIt() throws Exception { Logger leakTaskLogger = (Logger) LoggerFactory.getLogger("com.zaxxer.hikari.pool.ProxyLeakTask"); ListAppender appender = new ListAppender<>(); appender.start(); leakTaskLogger.addAppender(appender); HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:h2:mem:hikarileak;DB_CLOSE_DELAY=-1"); config.setUsername("sa"); config.setMaximumPoolSize(2); config.setLeakDetectionThreshold(2000); // the floor itself -- the shortest value that "counts" dataSource = new HikariDataSource(config); assertThat(config.getLeakDetectionThreshold()) .as("2000ms is exactly at the floor, so unlike 500ms above, it is NOT disabled") .isEqualTo(2000L); // Deliberately leaked: checked out and never closed within this test method. Connection leaked = dataSource.getConnection(); long deadline = System.currentTimeMillis() + 8000; while (appender.list.isEmpty() && System.currentTimeMillis() < deadline) { Thread.sleep(100); } assertThat(appender.list) .as("HikariCP's own leak-detection background task should have logged by now") .isNotEmpty(); String warning = appender.list.get(0).getFormattedMessage(); System.out.println("RESULT[hikari-leak-detection]: leakDetectionThreshold=2000ms | logger=" + leakTaskLogger.getName() + " | level=" + appender.list.get(0).getLevel() + " | message=" + warning); assertThat(warning) .as("HikariCP's own leak-detection task logs a WARN naming the pool and the stack " + "trace of where the connection was checked out, once it's been held longer " + "than leakDetectionThreshold") .contains("Connection leak detection triggered"); leaked.close(); // clean up now that the test has what it needs leakTaskLogger.detachAppender(appender); } }