Observer methods being called multiple times
fridgebuzz Feb 20, 2009 9:50 PMI'm having a problem in which two methods @observe the same event. This should be ok, I guess--there is nothing in the documentation to preclude it and it seems to be a normal way to use an observer pattern.
However, the result is that one of the two methods is being called twice.
To get specific, since I don't know what's causing this, the first method is in an application-scoped component. Two developers are working on this project and I didn't write this one, but it looks something like this:
@Name("registrationBookkeeper")
@Scope(ScopeType.APPLICATION)
public class RegistrationBookKeeper {
@Logger private Log log;
private int cnt = 0;
@Observer("userRegistered")
synchronized public void record(User user) {
cnt++;
log.info("User registered: username: " + user.getUserName());
log.info(cnt + " users have registered since the last restart");
}
}
The second is in a conversation-scoped component and looks something like this:
@Observer("userRegistered")
public void setDefaultProfileImage(User user) {
Image profileImage = imageHome.getInstance();
profileImage.setType(Image.ImageType.PROFILE);
profileImage.setFileName("/img/default-user.png");
profileImage.setFormat("image/png");
profileImage.setWidth(50);
profileImage.setHeight(50);
profileImage.setUser(user);
imageHome.persist();
user.setProfileImage(profileImage);
update();
}The event is raised when a User object is persisted, i.e. in UserHome.persist():
@Override
public String persist() {
User user = getInstance();
// do some stuff
// ...
String outcome = super.persist();
if (outcome == "persisted") {
if (Events.exists()) {
Events.instance().raiseEvent("userRegistered", user);
}
}
return outcome;
}
Looks fine, right? But the second @Observer method (setDefaultProfileImage) is called twice for a single raising of the event userRegistered. I'm not sure if it's causing grief or not, but certainly the potential for it is there and I would prefer this did not happen.
Is this behaviour expected? Can it be explained? Can it be avoided?
Thanks in advance for any replies.
Cheers,
Vanessa