Video tayyorlanmoqda

Bu JDBC kodi bir necha soat ishlagach "Connection is not available, request timed out" xatosini bera boshlaydi. Muammo nimada?

public Optional<String> findEmail(long id) throws SQLException {
    Connection con = dataSource.getConnection();
    PreparedStatement ps = con.prepareStatement("SELECT email FROM users WHERE id = ?");
    ps.setLong(1, id);
    ResultSet rs = ps.executeQuery();
    if (!rs.next()) {
        return Optional.empty();
    }
    String email = rs.getString(1);
    rs.close(); ps.close(); con.close();
    return Optional.of(email);
}

Xato chiqqanda yoki ResultSet bo'sh bo'lganda close() chaqirilmaydi, ulanish pool'ga qaytmaydi — connection leak. Vaqt o'tib pool'dagi hamma ulanish "osilib" qoladi. Yechim — try-with-resources.

📖 Javob

Bu yerda ikki teshik bor: foydalanuvchi topilmasa — return Optional.empty() hech narsani yopmaydi; executeQuery yoki getString exception tashlasa — ham yopilmaydi. Har bir shunday chaqiruv pool'dan bitta ulanishni abadiy "o'g'irlaydi". 10 talik pool bo'lsa, 10 ta topilmagan id'dan keyin ilova to'xtaydi.

To'g'ri yozilishi:

public Optional<String> findEmail(long id) throws SQLException {
    String sql = "SELECT email FROM users WHERE id = ?";
    try (Connection con = dataSource.getConnection();
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setLong(1, id);
        try (ResultSet rs = ps.executeQuery()) {
            return rs.next() ? Optional.of(rs.getString(1)) : Optional.empty();
        }
    }
}

Resurslar teskari tartibda, har qanday holatda yopiladi.

Prodda leak'ni topish uchun HikariCP'da leakDetectionThreshold bor:

spring.datasource.hikari.leak-detection-threshold: 20000   # 20 s

Ulanish shuncha vaqt qaytmasa, logga uni olgan joyning stack trace'i yoziladi. Spring'ning JdbcTemplate yoki JPA ishlatsangiz, bu muammo deyarli yo'qoladi — ular ulanishni o'zlari boshqaradi.