Skip to content

Close class resource InputStream in ThrowawayClassLoader#36933

Open
junhyeong9812 wants to merge 1 commit into
spring-projects:mainfrom
junhyeong9812:fix/throwawayclassloader-close-stream
Open

Close class resource InputStream in ThrowawayClassLoader#36933
junhyeong9812 wants to merge 1 commit into
spring-projects:mainfrom
junhyeong9812:fix/throwawayclassloader-close-stream

Conversation

@junhyeong9812

Copy link
Copy Markdown

Overview

ThrowawayClassLoader#loadClassFromResource opens an InputStream via
getResourceAsStream(...) but never closes it. The stream leaks on both the
success path (after defineClass) and the IOException path, since the
surrounding try block has neither a finally nor a try-with-resources.

InputStream inputStream = this.resourceLoader.getResourceAsStream(resourceName);
if (inputStream == null) {
    return null;
}
try {
    ...
    return defineClass(name, bytes, 0, bytes.length); // stream never closed
}
catch (IOException ex) {
    throw new ClassNotFoundException(...);             // stream never closed
}

Fix

Adopt the existing inputStream variable as a try-with-resources resource so it
is closed on every path, leaving the loading logic unchanged:

try (inputStream) {
    ...
}

A regression test (ThrowawayClassLoaderTests) verifies the stream is closed by
routing a tracked InputStream through the resource fallback path.

ThrowawayClassLoader#loadClassFromResource opened an InputStream via
getResourceAsStream(...) but never closed it. The stream leaked on both
the success path (after defineClass) and the IOException path, as the
surrounding try block had neither a finally nor a try-with-resources.

Adopt the existing inputStream variable as a try-with-resources resource
so that it is closed on every path, leaving the loading logic unchanged.

Signed-off-by: junhyeong9812 <pickjog@gmail.com>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Jun 16, 2026
@sbrannen sbrannen added in: core Issues in core modules (aop, beans, core, context, expression) type: enhancement A general enhancement and removed status: waiting-for-triage An issue we've not yet triaged or decided on labels Jun 16, 2026
@sbrannen sbrannen added this to the 7.1.0-M1 milestone Jun 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

in: core Issues in core modules (aop, beans, core, context, expression) type: enhancement A general enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants