开发者

Synchronize on value, not object [duplicate]

This question already has answers here: Synchronizing on String objects in Java (20 answers) Closed 5 years ago.

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.


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.


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.


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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜