I want to do something like this in Java
public void giveMoney(String userId, int money) {
synchronized (userId) {
Profile p = fetchProfileFromDB(userId);
p.setMoney(p.getMoney() + userId);
saveProfileToDB(p);
}
}
But of course, synchronizing on a string is not correct. What's a correct way to do something like this?
If the set of user ids is limited, you can synchronize on an interned version of the String
.
Either use String.intern()
(which has a few drawbacks) or something like Guava Interners
if you need a bit more control over the interning.