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条回答
Lonely孤独者°
2楼-- · 2019-03-18 20:08

What about this:

String userId = ...;
Object userIdLock = new Object();
synchronized (userIdLock) {
    Profile p = getProfile(userId);
    p.setMoney(p.getMoney() + p);
    saveProfile(p);
}

It's simple and above all obvious.

查看更多
放我归山
3楼-- · 2019-03-18 20:17

Based on your example, I assume you want to obtain a lock to a profile class, change it, and then release the lock. Synchronization is not exactly what you need in my opinion. You need a class that manages those records and lets you lock and unlock a record when changes need to be made to it, aka source control style.

Check this out: Lock class Java 5

查看更多
爷、活的狠高调
4楼-- · 2019-03-18 20:19

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.

查看更多
一夜七次
5楼-- · 2019-03-18 20:19

Theoretically speaking, since interned objects can be GC-ed, it's possible to synchronized on different objects (of the same value) at different times. Mutual exclusivity is still guaranteed, since it's not possible to synchronized on different objects at the same time.

However, if we synchronized on different objects, the happens-before relation is at doubt. We have to examine the implementation to find out. And since it involves GC, which Java Memory Model does not address, the reasoning can be quite difficult.

That's a theoretical objection; practically I don't think it'll cause any problem.

Still, there can be simple, direct, and theoretically correct solution to your problem. For example Simple Java name based locks?

查看更多
做自己的国王
6楼-- · 2019-03-18 20:24

In principle, you can synchronize on any object in Java. It's not in itself "not correct" to synchronize on a String object; it depends on what exactly you're doing.

But if userId is a local variable in a method, then this is not going to work. Each thread that executes the method with have its own copy of the variable (presumably referring to a different String object for each thread); synchronizing between threads ofcourse only works when you make multiple threads synchronize on the same object.

You'd have to make the object you're synchronizing on a member variable of the object that contains the method in which you have the synchronized block. If multiple threads are then calling the method on the same object, you'll achieve mutual exclusivity.

class Something {
    private Object lock = new Object();

    public void someMethod() {
        synchronized (lock) {
            // ...
        }
    }
}

You could also use explicit locks from the java.util.concurrent.locks package, that can give you more control if you need that:

class Something {
    private Lock lock = new ReentrantLock();

    public void someMethod() {
        lock.lock();
        try {
            // ...
        } finally {
            lock.unlock();
        }
    }
}

Especially if you want an exclusive lock for writing, but you don't want threads to have to wait for each other when reading, you might want to use a ReadWriteLock.

查看更多
戒情不戒烟
7楼-- · 2019-03-18 20:29

I guess there are a few options.

The easiest is that you could map a userId to a lock object in a threadsafe map. Others have mentioned interning but I don't think that's a viable option.

However, the more common option would be to synchronize on p (the Profile). This is appropriate if getProfile() is threadsafe, and by its name I would suspect it might be.

查看更多
登录 后发表回答