Synchronize on value, not object

Bart van Heukelom picture Bart van Heukelom · Sep 26, 2011 · Viewed 9.9k times · Source

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?

Answer

Joachim Sauer picture Joachim Sauer · Sep 26, 2011

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.