ValueLock

作者: 泠泉 | 来源:发表于2021-01-12 12:52 被阅读0次

    根据值进行加锁

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public enum ValueLock {
        MediaIdLock;
    
        ValueLock() {
            for (int i = 0; i < concurrencyLevel; i++) {
                locks[i] = new ReentrantLock();
            }
        }
    
        private int concurrencyLevel = 1 << 8; // 256locks
        private Lock[] locks = new Lock[concurrencyLevel];
    
        public Lock getLock(Object key) {
            return locks[key.hashCode() & (concurrencyLevel-1)]; // select one of 256 locks
        }
    
    //    public static void main(String[] args) {
    //        Lock mediaIdLock = ValueLock.MediaIdLock.getLock(11);
    //        try {
    //            mediaIdLock.lock();
    //            // do something
    //        } finally {
    //            mediaIdLock.unlock();
    //        }
    //    }
    }
    

    相关文章

      网友评论

          本文标题:ValueLock

          本文链接:https://www.haomeiwen.com/subject/pvwsaktx.html