Skip to content

Commit

Permalink
Delete old temporary files for the native lib at start-up time (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
odaira committed Sep 24, 2019
1 parent 7147f21 commit 08b3bff
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/java/net/jpountz/util/Native.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FilenameFilter;

/** FOR INTERNAL USE ONLY */
public enum Native {
Expand Down Expand Up @@ -67,11 +68,38 @@ public static synchronized boolean isLoaded() {
return loaded;
}

private static void cleanupOldTempLibs() {
String tempFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
File dir = new File(tempFolder);

File[] tempLibFiles = dir.listFiles(new FilenameFilter() {
private final String searchPattern = "liblz4-java";
public boolean accept(File dir, String name) {
return name.startsWith(searchPattern) && !name.endsWith(".lck");
}
});
if(tempLibFiles != null) {
for(File tempLibFile : tempLibFiles) {
File lckFile = new File(tempLibFile.getAbsolutePath() + ".lck");
if(!lckFile.exists()) {
try {
tempLibFile.delete();
}
catch(SecurityException e) {
System.err.println("Failed to delete old temp lib" + e.getMessage());
}
}
}
}
}

public static synchronized void load() {
if (loaded) {
return;
}

cleanupOldTempLibs();

// Try to load lz4-java (liblz4-java.so on Linux) from the java.library.path.
try {
System.loadLibrary("lz4-java");
Expand All @@ -87,8 +115,10 @@ public static synchronized void load() {
throw new UnsupportedOperationException("Unsupported OS/arch, cannot find " + resourceName + ". Please try building from source.");
}
File tempLib;
File tempLibLock;
try {
tempLib = File.createTempFile("liblz4-java", "." + os().libExtension);
tempLibLock = new File(tempLib.getAbsolutePath() + ".lck");
// copy to tempLib
FileOutputStream out = new FileOutputStream(tempLib);
try {
Expand All @@ -108,6 +138,9 @@ public static synchronized void load() {
}
System.load(tempLib.getAbsolutePath());
loaded = true;
if (!tempLibLock.exists()) {
new FileOutputStream(tempLibLock).close();
}
} finally {
try {
if (out != null) {
Expand All @@ -122,6 +155,9 @@ public static synchronized void load() {
} else {
// try to delete on exit, does it work on Windows?
tempLib.deleteOnExit();
if (tempLibLock.exists()) {
tempLibLock.deleteOnExit();
}
}
}
}
Expand Down

0 comments on commit 08b3bff

Please sign in to comment.