Sundararajan's Weblog

  • Java
    October 24, 2005

Weak references in JavaScript

Guest Author
Java access in Rhino JavaScript engine can be used to get
soft, weak references in scripts. For example, we may define the following script wrappers:

Object.prototype.softRef = function() {
return new java.lang.ref.SoftReference(this);
Object.prototype.weakRef = function() {
return new java.lang.ref.WeakReference(this);

Because we have added function properties to Object.prototype, we can create soft, weak references of any script object as shown below:

var x = "hello";
// create a SoftReference of script String 'hello'
x = x.softRef();
// may get null or "hello" depending on whether
// the SoftReference is cleared or not

Join the discussion

Comments ( 2 )
  • Attila Szegedi Friday, October 28, 2005
    Well, this will create a reference to the JavaScript object. It might be misleading with wrapped Java objects, as a casual developer could think he gets a reference to the underlying Java object, while in reality he gets a reference to the NativeJavaObject.
  • A. Sundararajan Saturday, October 29, 2005
    I agree that the soft/weak reference refers to the wrapper object (instance of NativeJavaObject etc.) and not directly to the underlying Java object. But, I think that is okay -- let us assume that there are no other references to Java object other than the NativeJavaObject that is wrapping it. If soft ref is cleared, then NativeJavaObject as well as the wrapped object become collectable by GC. The convenient illusion of treating NativeJavaObject as the underlying java object wrapped would work okay. Am I missing something?
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.