user11171
user11171

Reputation: 4071

Is my Swing app allocating redundant objects?

I've noticed that all Swing applications I've created seem to allocate new objects continuously.

Consider this small application:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings({ "javadoc", "serial" })
public class SwingTest extends JFrame {
    public static void main(String[] args) {
        new SwingTest().setVisible(true);
    }
    public SwingTest() {
        setTitle("SwingTest");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(400, 400));
        setContentPane(panel);
        pack();
    }
}

I wouldn't expect it to consume much memory, but if I look at the heap graph in VisualVM I see memory usage increasing constantly, then resetting. What causes this?

Upvotes: 0

Views: 212

Answers (2)

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

Preventing Java allocating new objects, so the garbage collection is less costly, is against one of the main principles the Java was build in the first place. No, there is no way Swing can be prevented creating new objects - how would it function, without its crucial objects? There is no special, no-object mode of operation.

If the performance of garbage collection is so crucial that it is a concern for you, then Java is not the technology you should be using. If your application is time-critical, write it in C or any other low-level language, where you have control over such things as memory management performance.

Upvotes: 1

barjak
barjak

Reputation: 11270

Here is the result of profiling your code on my machine (OpenJDK 1.6.0_22 64 bits on linux 3.1.1, using Netbeans profiler)

flat profiling result

I suggest you to find out what those allocated objects are. You can do this by making memory snapshots and comparing them.

Note that the Netbeans profiler is the same codebase than VisualVM.

Upvotes: 2

Related Questions