Category Archives: Hacks

Hacks used in building up Java2Script

Performance Matters or Not

Joel Spolsky had a post “Strategy Letter VI“. And I did agree with him to some degree when reading the post. And I decided to write a post about these opinions related to Java2Script later in the evening. And later in evening I found that Ajaxian’s Ben Galbraith posted his opinions but with title “Go Ajax, Young Man“. Well, the title said something already.

Here follows the Java2Script performance issues and SDK concerns.

Right now, performance is a really big matter to Java2Script. But does performance matter a lot in the future? That is a question.

Java2Script was open sourced in late of 2005. And now, 2 years has passed. And Firefox 2.0 is already released, while 2 year ago, it was still in its 1.0. And I could tell that the browser is improved a lot. OK, as I have paid lots of efforts in improving Java2Script performance, I think I would rather bet on the improvement of browser, the improvement of JavaScript engine (such as upgrading to Adobe’s script engine), upgrading of CPU and machine.

About performance, maybe a lot of developers complain that Java is slow. In fact, a lot of developer complains that Eclipse, which is Java based, is very slow and could not stand for it. But Java is still a language used by most of the developers in the last 4 or 5 years. And JavaScript is a language that is much slower than other language. But in recent three years, it is getting hotter and hotter in the format of AJAX development. No matter how slow it is.

Back to Java2Script. Java2Script compile Java sources to JavaScript, and Java2Script supports a port of desktop SWT library in JavaScript besides supporting most common java.* classes. The compilation from Java to JavaScript is done in a Java-way, that is to say, all information in Java sources are preserved in JavaScript, so lots of Java information and features are reserved, including Java reflection. And SWT library is considered a heavy weight library for JavaScript, as it was once designed for desktop application, not for web application.

Now come to comparison of Google Web Toolkit (GWT). GWT is a similar project when comparing to Java2Script. It contains a Java to JavaScript compiler, and supports a set of basic java.* libraries and a set of UI library. But the compilation of Java to JavaScript is not in the same way of Java2Script. It is in a C-way. It links all related JavaScript into a big JavaScript file. And those unrelated (unused) JavaScript are left without packing into the big JavaScript file. So you can not retrieve the Java class information from the final *.js file. But as compiling in C-way, the final *.js is a lot smaller than Java2Script’s *.js. And it also runs a lot faster than Java2Script’s. And the UI library of GWT is a new set of APIs. It is designed for web applications in browser only. So it is more browser-oriented and much more light weighted. In such a way, GWT’s performance is far faster than Java2Script. So few people cares about GWT’s performance.

In some simple words:
Java2Script is not optimized with more heavy weight SDK APIs
GWT is optimized in compiling with a light weight SDK APIs.

In fact, GWT is 100 times more popular than Java2Script at this writing time. So that means performance do matters. But what about 2 more years later? Is there any possibilities that GWT’s APIs is out and GWT’s early performance optimization is lagged behind the improvement of hardware and browser? Maybe later, AJAX developments prove that those optimized compiled *.js is not the trends, and web applications oriented UI APIs is not the trends for richer applications. But no one knows now. So as Ben Galbraith said:

itโ€™s hard to dispute that in a year or two, JavaScript will be much, much faster.

BTW: Java2Script 1.0.0 is to be released by the end of this September, even though performance is still a big problem (but not a huge problem now).

For more discussions, you may want to read early Java to JavaScript compiler discussions

Posted in Architecture, GWT, Hacks, JavaScript, SWT | 11 Comments

Asynchrony is Everything

You may know “Position is Everything” already. And I believe you should also know “Asynchony is Everything” or “Everything is Asynchronous” in RIA development.

Asynchrony is not only very important in web application development but also vital in normal desktop applications and embed systems. Asynchronous programming may help a lot in improving user experience. In normal desktop applications, if the main thread blocks UI for its long-time-consuming computing, users will feel desperately, waiting the busy-cursor to turn into default. But if such computing is run in background, user would find other things to do, such as switching focuses or typing something.

What about the definition of Asynchronous Computing? It is not only about asynchronous loading or asynchronous remote procedure call (RPC), it is also about local calculating. One thing should be mentioned here is UI layout computing. Lots of UI need complex layout calculating. For example, rendering a web page, rendering a 3D interfaces, or rending a complex dialog box. This CPU times required is especially obvious when it’s performed in a slow computer or in a slow computing environment, such as JavaScript runtime in browsers.

Here, I concerns about asynchronous layout. In implementing Java2Script’s SWT library, there is a huge problem for us. JavaScript is so slow that it can not finish a complex layout in less than 5 seconds. Or a complex layout requires more than 1 second will freeze browser UI, which make the user experience very bad and unacceptable. In order to overcome such problems. Java2Script introduced “Asynchronous Layout”.

Asynchronous layout is about to split the layout jobs into small pieces of jobs and run them step by step. As you may know, in SWT, all widgets are placed inside some containers. And to make a layout over container, the bounds of parent container, which is a Composite widget, is calculated first. And then the bounds will be passed as constraints of its child widgets to make children layouts. In such layout algorithms, we could split the layout jobs into parent container layout and child widget layout jobs, queue these jobs, and monitor each job’s required CPU times to avoid complex layout takes more than 200ms. If layout computing takes more than 200ms, then sleep for about 50ms before calling the next layout job.

Here are some snippets about Asynchronous Layout:

Display#readAndDispatch

public boolean readAndDispatch () {
checkDevice ();
drawMenuBars ();
runPopups ();
/*
if (OS.PeekMessage (msg, 0, 0, 0, OS.PM_REMOVE)) {
if (!filterMessage (msg)) {
OS.TranslateMessage (msg);
OS.DispatchMessage (msg);
}
runDeferredEvents ();
return true;
}
return runAsyncMessages (false);
*/

if (messageProc != 0) {
return true; //already hooked, return directly
}
messageProc = window.setInterval(new RunnableCompatibility() {
private boolean messageLoop = false;
public void run() {
runPopups ();
MESSAGE[] msgs = Display.this.msgs;
if (msgs.length == 0 && messageLoop)
/**
* @j2sNative
* var layoutFinished = window["j2s.swt.shell.finish.layout"];
* if (layoutFinished != null) {
* layoutFinished ();
* }
* this.messageLoop = false;
*/
{ }
if (msgs.length != 0) {
messageLoop = true;
MESSAGE[] defered = new MESSAGE[0];

int defsize = 0;
for (int i = msgs.length - 1; i >= 0; i--) {
MESSAGE m1 = msgs[i];
if (m1 == null) {
continue;
}
m1.defer = false;
for (int j = i - 1; j >= 0; j--) {
MESSAGE m2 = msgs[j];
if (m2 != null && m2.control == m1.control
&& m2.type == m1.type) {
msgs[j] = null;
}
}

if(m1.type == MESSAGE.CONTROL_LAYOUT){
if(m1.control.parent != null && m1.control.parent.waitingForLayout){
m1.defer = true;
defered[defsize++] = m1;
}
}

}
long time = 0;

for (int i = 0; i < msgs.length; i++) {
MESSAGE m = msgs[i];

if(m != null && m.defer){
continue;
}
msgs[i] = null;
if (m != null && m.type == MESSAGE.CONTROL_LAYOUT) {
m.control.waitingForLayout = false;
if (!m.control.isVisible()) { continue; }
Date d = new Date();
Composite c = (Composite) m.control;
if(c.waitingForLayoutWithResize){
c.setResizeChildren (false);
}
if(c.layout != null){
c.layout.layout (c, (c.state & Composite.LAYOUT_CHANGED) != 0);
c.state &= ~(Composite.LAYOUT_NEEDED | Composite.LAYOUT_CHANGED);
}
if(c.waitingForLayoutWithResize){
c.setResizeChildren (true);
c.waitingForLayoutWithResize = false;
}

if (m.data != null) {
boolean[] bs = (boolean[]) m.data;
c.updateLayout(bs[0], bs[1]);
} else {
c.layout();
}
time += new Date().getTime() - d.getTime();
if (time > 200) {
for (int j = i + 1; j < msgs.length; j++) {
msgs[j - i - 1] = msgs[j];
}
int length = msgs.length - i - 1;
for(int j = 0; j < defsize; j++){
msgs[length + j] = defered[j];
}
/**
* @j2sNativeSrc
* msgs.length -= i + 1;
* @j2sNative
* a.length -= f + 1;
*/
{}
return ;
}
}
}
/**
* @j2sNativeSrc
* msgs.length = 0;
* @j2sNative
* a.length = 0;
*/
{}
Display.this.msgs = defered;
// for(int j = 0; j < defsize; j++){
// msgs[j] = defered[j];
// }
}
}
}, 100);
return true;
}

Composite#updateLayout

void updateLayout (boolean resize, boolean all) {
if (isLayoutDeferred ()) return;
if ((state & LAYOUT_NEEDED) != 0 && !waitingForLayout) {
// boolean changed = (state & LAYOUT_CHANGED) != 0;
// state &= ~(LAYOUT_NEEDED | LAYOUT_CHANGED);
// if (resize) setResizeChildren (false);
// layout.layout (this, changed);
// if (resize) setResizeChildren (true);
this.waitingForLayout = true;
this.waitingForLayoutWithResize = resize;
display.sendMessage(new MESSAGE(this, MESSAGE.CONTROL_LAYOUT, new boolean[] {resize, all}));
}

if (all) {
Control [] children = _getChildren ();
int length = children.length;
for (int i=0; i<length; i++) {
// children [i].updateLayout (resize, all);
if (children[i] instanceof Composite) {
display.sendMessage(new MESSAGE(children[i], MESSAGE.CONTROL_LAYOUT, new boolean[] {resize, all}));
}
}
}
}

Control#setBounds:

void setBounds (int x, int y, int width, int height, int flags, boolean defer) {
/**
* A patch to send bounds to support mirroring features like what Windows have.
*/

boundsSet = true;
int tempX = x;
if(parent != null){
if((parent.style & SWT.RIGHT_TO_LEFT) != 0){
x = Math.max(0, parent.getClientArea().width - x - width);
}
}
Element topHandle = topHandle ();
if (defer && parent != null) {
forceResize ();
WINDOWPOS [] lpwp = parent.lpwp;
if (lpwp == null) {
/*
* This code is intentionally commented. All widgets that
* are created by SWT have WS_CLIPSIBLINGS to ensure that
* application code does not draw outside of the control.
*/

// int count = parent.getChildrenCount ();
// if (count > 1) {
// int bits = OS.GetWindowLong (handle, OS.GWL_STYLE);
// if ((bits & OS.WS_CLIPSIBLINGS) == 0) flags |= OS.SWP_NOCOPYBITS;
// }
if ((width != this.width || height != this.height)
&& this instanceof Composite) {
display.sendMessage(new MESSAGE(this, MESSAGE.CONTROL_LAYOUT, null));
}
this.left = x;
this.top = y;
this.width = width;
this.height = height;
SetWindowPos (topHandle, null, x, y, width, height, flags);
} else {
int index = 0;
while (index < lpwp.length) {
if (lpwp [index] == null) break;
index ++;
}
if (index == lpwp.length) {
WINDOWPOS [] newLpwp = new WINDOWPOS [lpwp.length + 4];
System.arraycopy (lpwp, 0, newLpwp, 0, lpwp.length);
parent.lpwp = lpwp = newLpwp;
}
WINDOWPOS wp = new WINDOWPOS ();
wp.hwnd = topHandle;
wp.x = x;
wp.y = y;
wp.cx = width;
wp.cy = height;
wp.flags = flags;
lpwp [index] = wp;
}
} else {
if ((width != this.width || height != this.height)
&& this instanceof Composite) {
display.sendMessage(new MESSAGE(this, MESSAGE.CONTROL_LAYOUT, null));
}
this.left = x;
this.top = y;
this.width = width;
this.height = height;
SetWindowPos (topHandle, null, x, y, width, height, flags);
}
/*
* The x coordination should be preserved, because the right to left emulation is just
* for the view, not the data!
*/

this.left = tempX;
}

For more details about Java2Script’s SWT Asynchronous Layout implementation, please check the sources history from SVN repository at http://j2s.svn.sourceforge.net/

Posted in Architecture, Hacks | 1 Comment

QoS of JavaScript

You must be aware of QoS when you are writing Rich Internet Application (RIA), especially when you are using AJAX. Why? And what aspects should be considered in QoS of RIA?

Here are some points:

1. Loading JavaScript file *.js by <script> tag may fail without acknowledge by the following JavaScript, which may result in a total page error;
2. Loading CSS style file *.css by <link> tag may fail, which results in ugly page layout;
3. Loading images by <img> tag may fail, which may confuse users;
4. …

The above scenarios do not occurs often in development period. Because you may using local HTTP server to serve resources, or you may have high bandwidth with slow latency. But if you deploy your applications to server, your server may be busy all the time to serve resources, and will fail to serve some resources at some uncertain time. And people may report such bugs if they are in beta tests, but people may lose their deals or money if such failures happen in real online.

So, QoS is required.

How to make sure the RIA’s qualities? First, make sure that such HTTP timeouts or failures does not interrupt normal business logics. To do so, try reload resources if such failures are detected. It would be easy to reload *.js file by <script> tag, or other resources by other tags. In order to detect failures, you may have your own loader. This is the reason why there is ClassLoader in Java2Script. To detect failures is also easy. Just hook the onerror or onreadystatechange event of loading JavaScript. Or you can setup a thread looping to check whether a *.css or an image is loaded or not.

There are other QoS aspects. Stay tuned for more coming discussions.

Posted in Architecture, Hacks, JavaScript | 6 Comments

Compressing and Deploying JavaScript

For AJAX, deploying JavaScript files may be important for you or not. If you are professional in AJAX, you must know the details of JavaScript deployment.

First, you can compress your JavaScript files before deploying them. Common compressors may cut 50% off of file size for normal JavaScript. That is to say, if your packed *.js is about 100k, the compressed *.js may be 50k. The compressed *.js may take about 100ms to decompress, but it when comparing to 50k over 1Mb/s bandwidth ( 50k * 8 / 1M = 0.4 s = 400ms). It worths such compressing. Usually bandwidth is not quite good as 1Mb/s, it will much better for compressed JavaScript.

Some well-known JavaScript compressors are Dean Edwards’ Packer and Shrink Safe by Alex at Dojo. You may find some other compressors, like Java2Script’s LZ77 JavaScript Compressor.

Second, you can send out your JavaScript files as gzip-encoded by Apache server. For most of modern browsers, gzip-encoding can be accepted. So you should configure your Apache server to do so especially when your JavaScript is over 200k. In common cases, gzip-encoding saves over 75% of JavaScript bandwidth. That is to say, 200k JavaScript only takes up 50k transmission. What a great improvement.

But please pay attention to some defects of JavaScript gzip-encoding for some browsers, like IE. Well, Internet Explorer takes up 80%+ of browser shares. You must not ignore IE’s defects on dealing JavaScript gzip-encoding. As IE6.0 SP2 and IE7+ already fixed this bug. You should support these two browsers, as it may get more and more market share.

So when configure .htaccess file for Apache httpd server, you should ignore those buggy IE browser or non-supported browsers. Here is my .htaccess file:

<IfModule mod_deflate.c>
# Netscape 4.x or IE 5.5/6.0
BrowserMatch ^Mozilla/4 no-gzip
# IE 5.5 and IE 6.0 have bugs! Ignore them until IE 7.0+
BrowserMatch \bMSIE\s7 !no-gzip
# IE 6.0 after SP2 has no gzip bugs!
BrowserMatch \bMSIE.*SV !no-gzip
# Sometimes Opera pretends to be IE with "Mozila/4.0"
BrowserMatch \bOpera !no-gzip
AddOutputFilterByType DEFLATE text/css text/javascript application/x-javascript
Header append Vary User-Agent
</IfModule>

For more information about this gzip-encoding configuration, please google “IE gzip javascript encoding” or read Joshua Eichorn’s blog article “Compressing JavaScript and CSS”.

Third, this is still about gzip-encoding. But this method tries to include JavaScript in HTML sources directly. As IE has no bugs on decoding gzip-encoded HTML files, compress JavaScript in this way will suite for most IE6 users. As far as I know, GWT uses this way to send out their JavaScript. But loading those HTML files in an embed IFRAME may make the whole architecture a little strange or hard to understand. Few people uses this method.

Maybe there are some other ways to compress and deploy JavaScript. Please let me know or discuss with me if you have a new one.

Posted in Architecture, Hacks, JavaScript | 24 Comments

Packing in Java2Script

Usually, when you develop new features, you split functions into pieces and implement them one by one. And in Java development, there will be implemented by one *.java file and another. If you want to deploy the finished feature, you need to pack them up.

In Java development, deployment means that you need to pack compiled *.class files and other related resource files into a *.jar and place it to correct location. There are lots of tools to do this job. Or if you are using IDE, such as Eclipse, the IDE will provide a whole development life management tools for you.

In JavaScript world, tools are rare. And for the loading speed and performance considerations, packing JavaScript and deploy them need your attentions.

Small *.js file should be packed into some bigger *.js file. But each *.js file should not be too big, or each time you update only one small *.js, you have to update a big *.js file. But *.js files should not be too many. Because *.js files are downloaded from servers in some specific orders, two many *.js files may be queued, which may mean a long latency. Lots of *.js compiled from *.java by Java2Script compiler is very small. In order to get a shorter loading time, most of these *.js files are packed into a big *.z.js file. Please check out the packing ant script. But packing *.js into a big *.z.js is not a simple job in Java2Script. As there is ClassLoader inside Java2Script system. The packed *.z.js file must be dealt correctly by ClassLoader. This issue is very complicate. And I would like to talk about it in another post.

Small size images can be packed into a bigger size one two. This is especially useful if there are icons for tool-bar. When a small icon needed, just display the big image with given position and size. This trick is a CSS tip. For example, create a DIV block with size 16×16, and set its style with some background image started from given position:

<div style="width:16px; height:16px; background-image:url(big.gif); background-position:16px 32px; background-repeat:no-repeat;"></div>

“background-position:16px 32px;” means the icon place at the 2nd row, the 3rd column. That is the image packing trick. Java2Script SWT implementation uses these tricks, you can check the Shell.css. In there, there are no absolute positions but relative positions, such as “center right”. This is because 9 icons are packed as 3×3 squares.

Small *.css can also be packed into a big *.css files too. But in practices of Java2Script packing, *.css files are packed into *.js files. All *.css files are only applied when necessary. For example, when a widget is loaded, the widget related *.css rules are applied to the page so that widget may be in correct style. For this trick, please check Java2Script CSS hacks.

And there are also some other packing tricks which I may introduce later. As packing is for deployment. And deployed resources are for loading. And loading will affect the whole object oriented inheritance simulator. And things are a whole integrated system.

Posted in Architecture, Hacks | 2 Comments

Asynchronous Programming

In my early Java2Script development days, I think a lot about asynchronous programming. AJAX was hot and is still hot. What is most important factor in AJAX technologies? I think it is “Asynchronous”. Without asynchronous programming, visitors still need to waste their time waiting for browser to fetch the next page. What a bad user experience.

In fact, asynchronous programming is not an easy work. Lots of callbacks, lots of threads, lots of locks or semaphores. All these stuffs may be messed up into an unmaintainable geeky thing.

Actually, if there are tools helping to design and maintain such codes, it is not a big job. If you use Java, you won’t get stuck at those threads of synchronized locks, as lots of debug tools help you figure out how those things work together at any moment you want to take a look. In fact, there are lots asynchronous programmings in Java design patterns or codes. But in Java world, asynchronous programming is not an outstanding features, and it is seldom discussed as an important issue.

But in JavaScript world, in browser world, asynchronous programming is a huge thing. In JavaScript (also known as EMCAScript)? language specification, there are no threads, no semaphores, no locks. All things are designed in synchronized mode. And before AJAX was hot, there are no robust tools for developers to write and debug JavaScript. If JavaScript sources file size exceeds 100K, it would be a hard-ass job to maintain. And if there are 3 layers of callbacks, it would drive developers crazy to develop new features. From my early experience, I designed a web form with digital signature functions, I used Java Applet in the back-end and used AJAX-style dialogs. And in oder to make a correct call from dialogs to Java Applet, its parameters may be passed through about 4-6 callback layers, because there are security issues over JavaScript calling Java Applet and Java Applet’s own sandbox mechanism. At that time, I sometimes found myself at the peak of being crazy or being collapsed.

So as I explain, asynchronous programming is not funny. And we would like to accept synchronous programming. Now let’s take a look at those Java synchronous programming which need to be JavaScript asynchronous programming:

Java snippet:

Display display = Display.getDefault();
SimpleSWTRPC shell = new SimpleSWTRPC(display, SWT.SHELL_TRIM);
shell.open();
shell.layout();
while (!shell.isDisposed()) { // waiting loop
if (!display.readAndDispatch())
display.sleep();
}
// continue other codes...

But in JavaScript, the above waiting loop will use up all CPU times and freeze browser. So such waiting loop must be avoided. And callback mechanism is used:

var display = $wt.widgets.Display.getDefault ();
var shell = new org.java2script.demo.simplerpc.SimpleSWTRPC (display, 1264);
shell.open ();
shell.layout ();
Sync2Async.block (shell, this, function () {
// continue other codes...
});

The above codes use Sync2Async technology. Such technologies have lots of defects. The biggest defect is that it can not stop browser to execute the following codes outside the method closure. For example, if the above codes are in method #openUpDialog, and in another method say #setUp call this method and then call other methods:

this.openUpDialog();
this.checkState();
this.sendOutRequest();

When the above codes are executed in Java mode, #checkState and #sendOutRequest will never be called until user closes the dialog. But in JavaScript Sync2Async mode, the callback technology can not block browser from executing #checkState and #sendOutRequest, which may result in incorrect result. This is the key defect of Sync2Async technology. Even though it has defects, such technology helps developes a lots for some simple tasks.

In order to fulfill some complicate task, designers should design the whole architecture as asynchronous programming patter from the beginning. Even in Java language, all things in asynchronous mode are still difficult.

More should be discussed for this issue.

Posted in Architecture, Hacks | 17 Comments

JDT Compiling and Java2Script Compiling

One feature that I like Java2Script is its full integration with Eclipse JDT’s incremental building.

Java2Script reuses Eclipse JDT to compile *.java into *.js. As Eclipse JDT supports incremental building, so Java2Script also supports this feature. The magic is that when a *.java file is passed into JDT’s ImageCompiler, it is also passed through Java2ScriptImageCompiler.

To understand JDT’s incremental building, when a *.java is modified and compiled, this file will be compiled, and as always, this modification may affect other *.java files, that is to say, some other classes may need recompiling. JDT uses some algorithms to figure out those delta *.java and compile it, and compiling continues until there is no affected files that need to be compiled.

As compiling has its entry, Java2Script just install an extra compiler at the entry so that a *.java file is compiled into *.class, it also be compiled into *.js. This is? the whole magic of Java2Script builder.

But to inject a Java2Script compiler into existed JDT plugin requires some works. First JDT’s compiler is not designed to be injected. Modified the JDT sources and recompiling the plugin do works. But it’s not quite suitable for public, as it need to overwrite original JDT plugin jars. There is another factor that make a little difficult in implementing Java2Script compiler based JDT. A lot of classes in JDT are package accessible or their methods are not public. It need a lot of works to do so that those restricts can be avoided. And besides, Java2Script compiler codes must be maintainable, or when a new Eclipse version is released, all those hard works need to re-do.

In current Java2Script compiler, it reuses codes in package org.eclipse.jdt.internal.core.builder. All it need is to move all the sources into a new package named net.sf.j2s.core.builder. And some new proxy classes or new inherited classes are added so it is possible to access inner data structure. And Java2ScriptImageCompiler is injected into those JDT normal compiling process. And there are some tricks here. To convert some instances between two different classes without trigger ClassClastError, one instance (e.g. net.sf.j2s.core.builder.State instance) is serialized into DataInputStream first, and then it will be de-serialized into another instance (org.eclipse.jdt.internal.core.builder.State.). In all, in implementing Java2Script compiler, it use all kinds of tricks to expose JDT’s inner data structures to outside compilers.

For more details, please compare the Java2Script sources (net.sf.j2s.core.builder, net.sf.j2s.core.compiler) with sources in JDT (org.eclipse.jdt.internal.core.builder, org.eclipse.jdt.core.compiler)

Posted in Hacks | 2 Comments

IE Hack: JavaScript Memory Leaks

The following is an article that I posted about one and a half years ago. I just repost it here as this is a hack to build up Java2Script Pacemaker.

—————————————————-

Yes, I knew there was JavaScript memory leak in IE. I developed JavaScript codes mainly by Firefox/Mozilla, so I won’t notice the codes were leaking memory. These days I was developing J2S application in Eclipse, and found that the J2S applications were runnig more and more slowly in the J2S Console, which embed IE Browser widget. Once I did not think that memory leaking will make such poor performance. The slowness that I couldn’t stand finally taught me the lesson and I decided to fix the leaking codes.

Searching the net, I found that lots of articles were talking about this problem. I mainly read Justin Rogers’ Understanding and Solving Internet Explorer Leak Patterns. And after finishing the articles, I monitored one J2S SWT application (SWT Tree Snippet) while tring to refresh the page. I found 5 times of refreshing will leaking the memory from about 22M to 31M! Then I knew that maybe about 100M+ of memories was leaked in developing J2S applications when I felt the slowness of J2S Console.

I added a handler to the “onunload” event to break those circular references, codes like following:

/*
* Only IE need to release the resources so that no memory is leaked
*/
if (window.attachEvent) {
window.attachEvent (“onunload”, function () {
try {
org.eclipse.swt.widgets.Display.releaseAllResources ();
} catch (e) {
}
return true;
});
}

In the static method org.eclipse.swt.widgets.Display.releaseAllResources, I set those elements’ on* handlers to null and set those Controls’ parent and children to null. Things did work much better. But it was not fixed compeletely. Once I refreshed for a couple of times, I noticed that the browser will leak some 10~100k gradually. That was to say it will take about 10~100 times of refreshing for about 1M leaking and users will only perceive the slowness after about 1000 times of refreshing. So it was considered as working better.
I tried other ways to solve this leaking but did not get the right entrance.The current Java2Script library is almost built on closures of JavaScript, which will leak memory easily and hide leadking codes deep inside the whole codes. Replacing all those codes that using closures? No. Without closures, it’s somewhat hard to implement the Java Class inheritance.

It’s as Justin Roger’s saying “not all memory leaks are easy to find”. Memory leaking is just awful enough! ๐Ÿ™

Posted in Hacks | 37 Comments