This question already has an answer here:
- Synchronizing on String objects in Java 17 answers
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?
You can use a proxy object for the string.
Use this mutex whenever you access
userId
.