loading file twice locks the file

yikes aroni yikesaroni at gmail.com
Thu Feb 1 13:19:14 UTC 2018

I find that, when i load a javascript file in java *twice *using this

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)

Try it with this code. Instructions:

1) Create a file "test.js" and put it where you want. I put it in

(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
private static ScriptEngine scriptEngine = nashornFactory.getScriptEngine();

private static void deleteFile(String sPath) throws IOException {
Path p = Paths.get(sPath);
private static void pause(int numsecs) {
int x;
try {
for (int i=0;i<numsecs;i++) {
x = i;
} catch (InterruptedException e) {

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("Sleeping ... ");
if (loadSecondSom) {
System.out.println("loading and calling som2...");
ScriptObjectMirror som2 = (ScriptObjectMirror)scriptEngine.eval("load('" +
sPath + "');");

System.out.println("Sleeping ... ");

System.out.println("Attempting to delete the file from the fs...");
try {
} catch (IOException e) {
System.out.println("Cannot delete the file: "+e);

} catch (ScriptException e) {
// TODO Auto-generated catch block

More information about the nashorn-dev mailing list