Skip to content

Commit

Permalink
Use shutdown hook to delete temp files instead of File.deleteOnExit (#…
Browse files Browse the repository at this point in the history
…4578)

* Use shutdown hook to delete temp files instead of File.deleteOnExit

Previously, the JRubyClassLoader would make a .deleteOnExit() call for
the temp directory and each temp file it needed to create.  This results
in the string for each registered path being stored in a hash that
increases each time a new URL is loaded or new ScriptingContainer is
created.

This commit removes the .deleteOnExit() calls and instead registers a
shutdown hook just after the temp directory is initially created.  At
shutdown time, the hook would delete any remaining files and the temp
directory itself.  This should effectively result in the same user
behavior as before but with the benefit of the temp path strings no
longer taking up an increasing amount of memory the longer the process
runs.

* Wrap exceptions for JRubyClassLoader shutdown delete with log statements

For any cases where the shutdown hook in the JRubyClassLoader encounters
an exception when trying to cleanup temp files, the exception should now
be caught and logged.
camlow325 authored and kares committed May 24, 2017
1 parent 154275c commit 205504b
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions core/src/main/java/org/jruby/util/JRubyClassLoader.java
Original file line number Diff line number Diff line change
@@ -60,7 +60,7 @@ public class JRubyClassLoader extends ClassDefiningJRubyClassLoader {

private Runnable unloader;

private File tempDir;
private static volatile File tempDir;

public JRubyClassLoader(ClassLoader parent) {
super(parent);
@@ -76,7 +76,6 @@ public void addURL(URL url) {
InputStream in = null; OutputStream out = null;
try {
File f = File.createTempFile("jruby", new File(url.getFile()).getName(), getTempDir());
f.deleteOnExit();
out = new BufferedOutputStream( new FileOutputStream( f ) );
in = new BufferedInputStream( url.openStream() );
int i = in.read();
@@ -110,15 +109,29 @@ public void addURL(URL url) {
super.addURL( url );
}

private File getTempDir() {
File tempDir = this.tempDir;
private static synchronized File getTempDir() {
if (tempDir != null) return tempDir;

tempDir = new File(systemTmpDir(), tempDirName());
if (tempDir.mkdirs()) {
tempDir.deleteOnExit();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
for (File f : tempDir.listFiles()) {
try {
f.delete();
} catch (Exception ex) {
LOG.debug(ex);
}
}
try {
tempDir.delete();
} catch (Exception ex) {
LOG.info("failed to delete temp dir " + tempDir + " : " + ex);
}
}
});
}
return this.tempDir = tempDir;
return tempDir;
}

private static final String TEMP_DIR_PREFIX = "jruby-";

0 comments on commit 205504b

Please sign in to comment.