From 8aa9e11342a27ef570618d258bf422fa3247b62b Mon Sep 17 00:00:00 2001 From: J-N-K Date: Sat, 1 Apr 2023 11:32:53 +0200 Subject: [PATCH] Fix resource leak in SysfsUsbSerialScanner (#3513) Signed-off-by: Jan N. Klug --- .../internal/SysfsUsbSerialScanner.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/bundles/org.openhab.core.config.discovery.usbserial.linuxsysfs/src/main/java/org/openhab/core/config/discovery/usbserial/linuxsysfs/internal/SysfsUsbSerialScanner.java b/bundles/org.openhab.core.config.discovery.usbserial.linuxsysfs/src/main/java/org/openhab/core/config/discovery/usbserial/linuxsysfs/internal/SysfsUsbSerialScanner.java index 2096ddd0e02..3efdb8389ed 100644 --- a/bundles/org.openhab.core.config.discovery.usbserial.linuxsysfs/src/main/java/org/openhab/core/config/discovery/usbserial/linuxsysfs/internal/SysfsUsbSerialScanner.java +++ b/bundles/org.openhab.core.config.discovery.usbserial.linuxsysfs/src/main/java/org/openhab/core/config/discovery/usbserial/linuxsysfs/internal/SysfsUsbSerialScanner.java @@ -154,16 +154,18 @@ private Set getSerialPortInfos() throws IOException { Path devSerialDir = Path.of(DEV_SERIAL_BY_ID_DIRECTORY); if (exists(devSerialDir) && isDirectory(devSerialDir) && isReadable(devSerialDir)) { // browse serial/by-id directory : - for (Path devLinkPath : newDirectoryStream(devSerialDir)) { - if (Files.isSymbolicLink(devLinkPath)) { - Path devicePath = getRealDevicePath(devLinkPath); - if (devicePath != null) { - String serialPortName = devicePath.getFileName().toString(); - // get the corresponding real sysinfo special dir : - Path sysfsDevicePath = getRealDevicePath( - Paths.get(sysfsTtyDevicesDirectory).resolve(serialPortName)); - if (sysfsDevicePath != null && isReadable(devicePath) && isWritable(devicePath)) { - result.add(new SerialPortInfo(devLinkPath, sysfsDevicePath)); + try (DirectoryStream directoryStream = newDirectoryStream(devSerialDir)) { + for (Path devLinkPath : directoryStream) { + if (Files.isSymbolicLink(devLinkPath)) { + Path devicePath = getRealDevicePath(devLinkPath); + if (devicePath != null) { + String serialPortName = devicePath.getFileName().toString(); + // get the corresponding real sysinfo special dir : + Path sysfsDevicePath = getRealDevicePath( + Paths.get(sysfsTtyDevicesDirectory).resolve(serialPortName)); + if (sysfsDevicePath != null && isReadable(devicePath) && isWritable(devicePath)) { + result.add(new SerialPortInfo(devLinkPath, sysfsDevicePath)); + } } } }