Reputation: 1054
I'm working on a Java Swing program. Could there be some performance degradation if I use the following approach?
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingWorker worker = new SwingWorker() {
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
// do stuff
}
};
worker.execute();
}
});
If I'm doing some heavy processing task inside done()
, is it better to define the SwingWorker
instance as a global member rather than a local anonymous class declaration?
I think if it's local, it's created every time actionPerformed
is invoked(is it?). Will using a global instance lead to increase in performance? Any differences in memory utilization in global/local approaches?
Upvotes: 1
Views: 348
Reputation: 36611
In your specific example, it is very easy to answer. A SwingWorker
is designed to be only run once, as specified in the class javadoc (see also this SO question)
SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice.
So in this case you will have to create a new instance each time the actionPerformed
is invoked.
Side-note: the heavy processing work should be done in the doInBackground
method, not in the done
method or you will block the EDT
Upvotes: 4