Synchronize on value, not object [duplicate]

2019-03-18 19:55发布

This question already has an answer here:

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?

7条回答
冷血范
2楼-- · 2019-03-18 20:35

You can use a proxy object for the string.

Object userIdMutex = new Object();

synchronized (userIdMutex) {
    Profile p = getProfile(userId);
    p.setMoney(p.getMoney() + p);
    saveProfile(p);
}

Use this mutex whenever you access userId.

查看更多
登录 后发表回答