Skip to content

[ISSUE #10208] Fix resource leak in IOTinyUtils.copyFile#10210

Open
daguimu wants to merge 1 commit intoapache:developfrom
daguimu:fix/iotinyutils-resource-leak-10208
Open

[ISSUE #10208] Fix resource leak in IOTinyUtils.copyFile#10210
daguimu wants to merge 1 commit intoapache:developfrom
daguimu:fix/iotinyutils-resource-leak-10208

Conversation

@daguimu
Copy link
Copy Markdown

@daguimu daguimu commented Mar 25, 2026

Problem

In IOTinyUtils.copyFile(), FileOutputStream and FileInputStream are created inline:

tc = new FileOutputStream(tf).getChannel();
sc = new FileInputStream(sf).getChannel();

The underlying stream references are lost. If new FileInputStream(sf) throws an exception (e.g., file locked), the already-created FileOutputStream and its channel will never be closed, leaking a file descriptor. The finally block only closes the FileChannel variables, which may be null at that point.

Root Cause

Stream objects are not stored in variables and therefore cannot be closed in the finally block if an exception occurs between their creation.

Fix

Refactored to use try-with-resources, which ensures all four resources (FileInputStream, FileOutputStream, and their channels) are properly closed in all cases:

try (FileInputStream fis = new FileInputStream(sf);
     FileOutputStream fos = new FileOutputStream(tf);
     FileChannel sc = fis.getChannel();
     FileChannel tc = fos.getChannel()) {
    sc.transferTo(0, sc.size(), tc);
}

Tests Added

No new tests needed — existing IOTinyUtilsTest.testCopyFile() covers the normal path and passes with the refactored code. The fix is a pure resource management improvement.

Impact

  • No behavioral change for normal operation
  • Fixes potential file descriptor leak on exception paths
  • Reduces code from 14 lines to 5 lines with cleaner resource management

Fixes #10208

FileInputStream and FileOutputStream were created inline as arguments
to getChannel(), losing the stream references. If an exception occurs
between the two stream creations, the first stream leaks. Refactored
to use try-with-resources for proper resource management.

Fixes apache#10208
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Resource leak in IOTinyUtils.copyFile - FileInputStream/FileOutputStream not closed on exception

1 participant