Potential URLClassLoader bug?

Patrick Reinhart patrick at reini.net
Thu Oct 10 14:13:35 UTC 2024


Hi Everybody,

I recently stumbled over a strange behavior within the URLClassLoader under Windows regarding a left open file handle even though everything is handled within try-with-resources blocks.

Here is simple test that passes under Linux & Mac but fails under Windows:


import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.jar.*;

public class TestURLClassLoader {

    public static void main(String[] args) throws Exception {
        var testJar = setupJar();
        try (URLClassLoader cl = new URLClassLoader(new URL[] { testJar.toUri().toURL() })) {
            var testResource = cl.getResource("testResource");
            assert testResource != null;
            try (InputStream in = testResource.openStream()) {
                in.transferTo(System.out);
            }
        }
        Files.delete(testJar);
        assert !Files.exists(testJar);
    }

    // setting up a simple .jar file with a single resource as example
    private static Path setupJar() throws IOException {
        var testJar = Paths.get("test.jar");
        try (var out = new FileOutputStream("test.jar");
             var jar = new JarOutputStream(out)) {
            jar.putNextEntry(new JarEntry("testResource"));
            var testData = "some data\n".getBytes();
            jar.write(testData, 0, testData.length);
        }
        assert Files.exists(testJar);
        return testJar;
    }
}


More information about the core-libs-dev mailing list