hi all,
I remembered that I read a book 5 years ago, saying that “Double-Checked Locking is Broken” in Java. But I find there are lots of “double check” in openfire. So could you tell me why?
Thanks,
hi all,
I remembered that I read a book 5 years ago, saying that “Double-Checked Locking is Broken” in Java. But I find there are lots of “double check” in openfire. So could you tell me why?
Thanks,
I read a book 5 years ago, saying that
5 years are a long time in this business. Wikipedia says:
As of J2SE 5.0, this problem has been fixed.
However, it seems that the volatile keyword is needed in these cases. Maybe someone should check this in detail.
Example: UserManager.getUser(String)
public User getUser(String username) throws UserNotFoundException {
if (username == null) {
throw new UserNotFoundException("Username cannot be null");
}
// Make sure that the username is valid.
username = username.trim().toLowerCase();
User user = userCache.get(username);
if (user == null) {
synchronized (username.intern()) {
user = userCache.get(username);
if (user == null) {
user = provider.loadUser(username);
userCache.put(username, user);
}
}
}
return user;
}
user is an local variable, so there is no sync needed. userCache is an instance of DefaultCache, so method get is sychronized. I see no problems here.