How to acquire a lock by a key

前端 未结 6 1354
一个人的身影
一个人的身影 2020-11-28 09:47

What is the best way to prevent concurrent update of one record in a key-value set without locking the entire set? Semantically, I\'m looking for some kind of locking by a k

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 10:25

    This is how; i did it. And yes I agree if two different strings shares the same hashcode will end up with acquiring the same lock.

    class LockByKey {
        ObjectForString objHolder = new ObjectForString(100);
        public void lockThenWorkForKey (String key) {
            synchronized(objHolder.valueOf(key)){
                //DoSomeWork
            }
        }
    }
    
    public final class ObjectForString {
    
        private final Object[] cache;
        private final int cacheSize;
        final int mask;
    
        public ObjectForString(int size) {
            // Find power-of-two sizes best matching arguments
            int ssize = 1;
            while (ssize < size) {
                ssize <<= 1;
            }
    
            mask = ssize - 1;
            cache = new Object[ssize];
            cacheSize = ssize;
            //build the Cache
            for (int i = 0; i < cacheSize; i++) {
                this.cache[i] = new Object();
            }
        }
    
        public Object valueOf(String key) {
            int index = key.hashCode();
            return cache[index & mask];
        }
    }
    

提交回复
热议问题