I have a cyclic property change listener set up. I have 2 objects of class A. I have made one object listen to changes of the other and vice versa. Here's the code:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CyclicPCLTest {
public static class A implements PropertyChangeListener{
private PropertyChangeSupport propertyChangeSupport;
private String date;
public A(String date) {
this.date = date;
propertyChangeSupport=new PropertyChangeSupport(this);
}
public String getDate() {
return date;
}
public void setDate(String date) {
String oldDate=this.date;
this.date = date;
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, "date", oldDate, this.date));
}
public void addPropertyChangeListener(PropertyChangeListener listener){
propertyChangeSupport.addPropertyChangeListener(listener);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
setDate ((String) evt.getNewValue());
}
}
public static void main(String[] args) {
List<A> as= Arrays.asList(new A[]{new A("01/02/2011"), new A("01/02/2011")});
as.get(0).addPropertyChangeListener(as.get(1));
as.get(1).addPropertyChangeListener(as.get(0));
as.get(0).setDate("02/02/2011");
System.out.println("date of the other A "+as.get(1).getDate());
as.get(1).setDate("03/02/2011");
System.out.println("date of the other A "+as.get(0).getDate());
}
}
The code works and this is the output:
date of the other A 02/02/2011
date of the other A 03/02/2011
I am wondering how it does? Shouldn't it give me a stackoverflow error? When the first A is updated it notifies the second A, the second A then gets updated and notifies the first A. This should go on for ever.
Thats because
firePropertyChange
will only fire the event ifoldValue
is not equal tonewValue
After 2 recursive runs, when the code reaches
the
oldDate
andthis.date
essentially become same (that isoldDate.equals(this.date) == true
) and it doesn't propagate the event to the listenersCheck the documentation of
firePropertyChange
method