Java threads locking on a specific object

前端 未结 10 837
抹茶落季
抹茶落季 2020-12-12 00:06

I have a web application and I am using Oracle database and I have a method basically like this:

public static void saveSomethingImportantToDataBase(Object t         


        
10条回答
  •  醉梦人生
    2020-12-12 00:24

    Here is an option adapted from And360's comment on Bohemian's answer, that tries to avoid race conditions, etc. Though I prefer my other answer to this question over this one, slightly:

    import java.util.HashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    
    // it is no advantage of using ConcurrentHashMap, since we synchronize access to it
    // (we need to in order to "get" the lock and increment/decrement it safely)
    // AtomicInteger is just a mutable int value holder
    // we don't actually need it to be atomic
    static final HashMap locks = new HashMap();
    
    public static void saveSomethingImportantToDataBase(Object objectToSave) {
        AtomicInteger lock;
        synchronized (locks) {
            lock = locks.get(objectToSave.getId());
            if (lock == null) {
                lock = new AtomicInteger(1);
                locks.put(objectToSave.getId(), lock);
            }
            else 
              lock.incrementAndGet();
        }
        try {
            synchronized (lock) {
                // do synchronized work here (synchronized by objectToSave's id)
            }
        } finally {
            synchronized (locks) {
                lock.decrementAndGet();
                if (lock.get() == 0)  
                  locks.remove(id);
            }
        }
    }
    

    You could split these out into helper methods "get lock object" and "release lock" or what not, as well, to cleanup the code. This way feels a little more kludgey than my other answer.

提交回复
热议问题