« November 2009
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
     
       
Today
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 1035

Powered by Roller Weblogger.
« Java overloaded... | Main | Which version of... »
20051024 Monday October 24, 2005

Weak references in JavaScript

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
x.get(); 





( Oct 24 2005, 06:42:42 PM IST ) Permalink Comments [2] del.icio.us | furl | simpy | slashdot | technorati | digg

Comments:

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.

Posted by Attila Szegedi on October 29, 2005 at 01:15 AM IST #

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?

Posted by A. Sundararajan on October 29, 2005 at 06:25 PM IST #

Post a Comment:

Comments are closed for this entry.
Copyright (C) 2005, A. Sundararajan's Weblog