nanode
02-08-2001, 11:23 AM
The other day I was presented with a challenge from someone who clearly wasn't a java fan, in particular, he hated SWING.
His claim was that creating new windows populated with widgets, then disposing them would ultimately cause massive memory leakage.
Below is some test code. Please excuse my arg. handling, I rarely write CLI apps in Java. :(
Running this should be self explanatory. Just be sure to add 'd' as the last arg if you want the windows to dispose.
So far, on win2k w/ jdk1.3 I created and disposed over 300,000 widgets and only lost about 2MB of RAM. I got twice that far on my Linux box (which had 1/2 the RAM as my work box).
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CrashMe {
public static void main(String[] args) {
int n = 0;
boolean dispose = false;
if (args.length > 0) {
n = Integer.valueOf(args[0]).intValue();
if (args.length == 2) {
if (args[1].equals("d")) { dispose = true; }
}
}
else {
System.out.println("Usage: java CrashMe [# instances] <d>");
System.exit(0);
}
for (int frames=0;frames<n;frames++) {
JPanel demo = new JPanel();
demo.setBackground(Color.white);
for (int i=0;i<n;i++) {
demo.add(new JButton("JButton #" + i));
}
JFrame f = new JFrame("Window #" + frames);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
f.getContentPane().add("Center", demo);
f.pack();
f.setSize(new Dimension(600,500));
f.show();
if (dispose) {
f.dispose();
}
}
System.out.println("Haha, I didn't crash");
}
}
His claim was that creating new windows populated with widgets, then disposing them would ultimately cause massive memory leakage.
Below is some test code. Please excuse my arg. handling, I rarely write CLI apps in Java. :(
Running this should be self explanatory. Just be sure to add 'd' as the last arg if you want the windows to dispose.
So far, on win2k w/ jdk1.3 I created and disposed over 300,000 widgets and only lost about 2MB of RAM. I got twice that far on my Linux box (which had 1/2 the RAM as my work box).
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CrashMe {
public static void main(String[] args) {
int n = 0;
boolean dispose = false;
if (args.length > 0) {
n = Integer.valueOf(args[0]).intValue();
if (args.length == 2) {
if (args[1].equals("d")) { dispose = true; }
}
}
else {
System.out.println("Usage: java CrashMe [# instances] <d>");
System.exit(0);
}
for (int frames=0;frames<n;frames++) {
JPanel demo = new JPanel();
demo.setBackground(Color.white);
for (int i=0;i<n;i++) {
demo.add(new JButton("JButton #" + i));
}
JFrame f = new JFrame("Window #" + frames);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
f.getContentPane().add("Center", demo);
f.pack();
f.setSize(new Dimension(600,500));
f.show();
if (dispose) {
f.dispose();
}
}
System.out.println("Haha, I didn't crash");
}
}