SwingWorker: clean up the mess before leaving

Of course you add a PropertyChangeListener to a SwingWorker's list of listeners to be informed of advances in the progress of computations and to notice changes in SwingWorker's status.

But, when do you remove those listeners? Of course if you don't remove listeners then you keep references from the SwingWorker to the listeners and that may lead to memory leaks.

Of course the safest place to remove listeners is when the SwingWorker is done. Something like this:

public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent)
{
  SwingWorker source = (SwingWorker) propertyChangeEvent.getSource();
  if ( "state".equals( propertyChangeEvent.getPropertyName() )
       && (source.isDone() || source.isCancelled() ) )
  {
    source.removePropertyChangeListener( this );
  }
}
So the listener removes itself when the SwingWorker is done. Easy and clean. So here we go with another suggestion for SwingWorkers:

SwingWorker suggestion IV: Clean up listeners when done Each PropertyChangeListener should remove itself from the list of listeners whenever the SwingWorker is done.
Enough for today. Keep swinging,
Antonio
Comentarios:

Enviar un comentario:
Los comentarios han sido deshabilitados.
About

swinger

Search

Archives
« abril 2014
lunmarmiéjueviesábdom
 
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
    
       
Hoy