I find that, when i load a javascript file in java *twice *using this pattern
ScriptObjectMirror som = scriptEngine.eval("load('c:/temp/test.js');"); it locks the JS file (prevents its deletion). This does NOT happen if i load the file only once. Furthermore, this happens even if i null out the resulting ScriptObjectMirrors. My question is: how can I avoid this? I need to be able to load the file and get the resulting ScriptObjectMirror multiple times and be able to delete the source file. Is Nashorn not properly closing a stream? It's odd that it doesn't lock the file for the first SOM, but does for the second (and subsequent) SOMs.... Try it with this code. Instructions: 1) Create a file "test.js" and put it where you want. I put it in c:\temp\test.js (function(module) { var exports = module.exports; exports.test = function() { return "test ok"; } return module.exports;})({exports:{}, id:'test'}); 2) Create a Temp.java as follows and run it first with *loadSecondSom = true*. The deletion will fail. Then run it with *loadSecondSom = false*. The deletion will succeed. (Note: the "pause" is only to make it clearer...) import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.script.ScriptEngine; import javax.script.ScriptException; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; import jdk.nashorn.api.scripting.ScriptObjectMirror; public class Temp { private static final NashornScriptEngineFactory nashornFactory = new NashornScriptEngineFactory(); private static ScriptEngine scriptEngine = nashornFactory.getScriptEngine(); private static void deleteFile(String sPath) throws IOException { Path p = Paths.get(sPath); Files.delete(p); } private static void pause(int numsecs) { int x; try { for (int i=0;i<numsecs;i++) { Thread.sleep(1000); x = i; } } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] ss) { boolean loadSecondSom = true; String sPath = "C:/temp/test.js"; try { System.out.println("loading and calling som1..."); ScriptObjectMirror som1 = (ScriptObjectMirror)scriptEngine.eval("load('" + sPath + "');"); System.out.println(som1.callMember("test")); System.out.println("Sleeping ... "); pause(2); if (loadSecondSom) { System.out.println("loading and calling som2..."); ScriptObjectMirror som2 = (ScriptObjectMirror)scriptEngine.eval("load('" + sPath + "');"); System.out.println(som2.callMember("test")); } System.out.println("Sleeping ... "); pause(2); System.out.println("Attempting to delete the file from the fs..."); try { deleteFile(sPath); } catch (IOException e) { System.out.println("Cannot delete the file: "+e); } System.out.println("DONE"); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }