From ef159db3203e00302c587bd0d4056ff723439c21 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Tue, 9 Aug 2016 17:59:18 +0200 Subject: [PATCH] Delete temporary .so file after loading Motivation: Our current strategy in NativeLibraryLoader is to mark the temporary .so file to be deleted on JVM exit. This has the drawback to not delete the file in the case the JVM dies or is killed. Modification: Just directly try to delete the file one we loaded the native library and if this fails mark the file to be removed once the JVM exits. Result: Less likely to have temporary files still on the system in case of JVM kills. --- .../util/internal/NativeLibraryLoader.java | 42 ++++++++----------- 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java index 2f5a00836b..711efaf652 100644 --- a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java +++ b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java @@ -18,6 +18,7 @@ package io.netty.util.internal; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; +import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -196,7 +197,6 @@ public final class NativeLibraryLoader { InputStream in = null; OutputStream out = null; File tmpFile = null; - boolean loaded = false; try { tmpFile = File.createTempFile(prefix, suffix, WORKDIR); in = url.openStream(); @@ -208,37 +208,29 @@ public final class NativeLibraryLoader { out.write(buffer, 0, length); } out.flush(); - out.close(); - out = null; System.load(tmpFile.getPath()); - loaded = true; } catch (Exception e) { throw (UnsatisfiedLinkError) new UnsatisfiedLinkError( "could not load a native library: " + name).initCause(e); } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ignore) { - // ignore - } + safeClose(in); + safeClose(out); + // After we load the library it is safe to delete the file. + // We delete the file immediately to free up resources as soon as possible, + // and if this fails fallback to deleting on JVM exit. + if (tmpFile != null && !tmpFile.delete()) { + tmpFile.deleteOnExit(); } - if (out != null) { - try { - out.close(); - } catch (IOException ignore) { - // ignore - } - } - if (tmpFile != null) { - if (loaded) { - tmpFile.deleteOnExit(); - } else { - if (!tmpFile.delete()) { - tmpFile.deleteOnExit(); - } - } + } + } + + private static void safeClose(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException ignore) { + // ignore } } }