1

I am using Rhino to embed JavaScript in a Java class. I wanted to create multiple Scriptable scopes using a parent Global scope, but I can't figure out when or how the scopes will be cleaned up (garbage collected). I just want to ensure that I'm not leaking memory with the scopes.

A brief example of what I want to do:

private Global parentScope;
private Context cx;

public MyClass() {
    cx = ContextFactory.getGlobal().enterContext();
    cx.setOptimizationLevel(-1);
    cx.setLanguageVersion(Context.VERSION_1_5);
    parentScope = new Global(cx);
}

public Scriptable createNewChildScope() {
    Scriptable scope = cx.newObject(parentScope);
    scope.setPrototype(null);
    scope.setParentScope(parentScope);
    return scope;
}

Now if I created a bunch of child scopes how and when would they know to be cleaned up? Are they just POJOs that will be cleaned up by whatever GC algorithm is being used, or is there a chance that I'll have a memory leak through the context?

Thank you!

AndyJW
  • 191
  • 8

1 Answers1

0

Though the scopes refer to javascript, the objects are Java, so they must follow Java garbage collection rules. I think there are two questions implied here:

  1. When does garbage collection happen?
  2. What gets collected?

You can't and shouldn't attempt to predict when garbage collection will happen--you should assume it could happen at any time. That may be obvious, but I note it just for completeness.

You can predict what will may get collected: anything that is unreferenced. So if there is a reference in Java to the scope objects they will not be garbage collected. If the parentScope kept references to them, they would exist as long as the parentScope was referenced, but I don't see way to get to the child scopes from the parentScope. You can remove references to an object by assigning null or leaving the block where it was declared.

Scriptable scope1 = createNewChildScope();
Scriptable scope2 = createNewChildScope();
// ...
scope1 = createNewChildScope(); // first allocated scope can be garbage collected
// scope2 is still safe

(Similarly, as long as the scope exists, any javascript objects inside the scope would follow similar garbage collection rules in their own language.)

Community
  • 1
  • 1
sbcondor
  • 71
  • 3
  • Thank you for the garbage collection fundamentals. I guess my question was poorly worded. I want to know if I'm going to leak memory or not. – AndyJW Jun 18 '14 at 21:11