jakartaee / mail-api

Jakarta Mail Specification project
https://jakartaee.github.io/mail-api
Other
240 stars 100 forks source link

Master SharedFileInputStream closes unexpectedly #694

Closed SeongEon-Jo closed 6 months ago

SeongEon-Jo commented 11 months ago

Describe the bug Master SharedFileInputStream closes unexpectedly after GC even if some slave SharedFileInputStream(constructed by newStream()) are still being referenced.

Detailed exception is IOException: Stream Closed

To Reproduce Steps to reproduce the behavior:

Here's a simple failing test case to reproduce the error.

@Test
void test() throws Exception {
    // you can use any file to test
    File file = Paths.get("src/test/resources/test_file.jpeg").toFile();

    InputStream slaveSharedFileIs = new SharedFileInputStream(file).newStream(0, -1);

    System.gc();

    Assertions.assertDoesNotThrow(() -> slaveSharedFileIs.read());
}

I guess master SharedFileInputStream which is not referenced anymore calls finalize() and close() when GC works, so slave SharedFileInputStream also cannot access the file after that.

To prove, the test case below succeeds.

@Test
void test() throws Exception {
    // you can use any file to test
    File file = Paths.get("src/test/resources/test_file.jpeg").toFile();

    SharedFileInputStream masterSharedFileIs = new SharedFileInputStream(file);

    InputStream slaveSharedFileIs = masterSharedFileIs.newStream(0, -1);

    System.gc();

    Assertions.assertDoesNotThrow(() -> slaveSharedFileIs.read());
}

Expected behavior RandomAccessFile should not be closed when there is at least one of remaining SharedFileInputStream still being referenced(used)