spotify-web-api-java/spotify-web-api-java

[Bug] Memory Leak (Unmanaged ThreadLocal) in SpotifyApi via SIMPLE_DATE_FORMAT

开放

#450 创建于 2026年2月20日

 (1 条评论) (0 个反应) (0 位负责人)HTML (290 个派生)auto 404
good first issuehacktoberfesthelp wanted

仓库指标

星标
 (1,076 个星标)
PR 合并指标
 (PR 指标待抓取)

描述

Bug Description In se.michaelthelin.spotify.SpotifyApi, the static field SIMPLE_DATE_FORMAT utilizes a ThreadLocal<SimpleDateFormat> to handle date parsing and formatting. However, there is no mechanism to call ThreadLocal.remove() to clean up the resource.

Reproduction Steps This issue triggers when the SDK is integrated into server-side gateway applications or any environment utilizing long-lived thread pools (e.g., Spring Boot default executors, Tomcat).

Minimal reproduction concept:

ExecutorService pool = Executors.newFixedThreadPool(200);
for (int i = 0; i < 10000; i++) {
    pool.submit(() -> {
        try {
            // Each thread in the pool initializes its own SimpleDateFormat
            SpotifyApi.parseDefaultDate("2023-01-01T12:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}
// The ThreadLocalMap of all 200 core threads will permanently hold a SimpleDateFormat instance, as .remove() is never invoked.



Impact
This Unmanaged ThreadLocal (UTL) usage leads to memory leaks. In high-concurrency environments with large thread pools, the uncollected SimpleDateFormat instances will gradually inflate the heap memory, potentially leading to performance degradation or OutOfMemoryError over time.

Suggested Fix
Since the project likely uses Java 8+, the most robust solution is to replace ThreadLocal<SimpleDateFormat> with java.time.format.DateTimeFormatter. DateTimeFormatter is immutable and inherently thread-safe, eliminating the need for ThreadLocal entirely.

贡献者指南