java 动态同步是个好主意还是允许的?

Is java dynamic synchronization a good idea or allowed?

基本上,需要的是将请求同步到每条记录。 我能想到的一些代码是这样的:

//member variable
ConcurrentHashMap<Long, Object> lockMap = new ConcurrentHashMap<Long, Object>();

//one method
private void maintainLockObjects(long id){
    lockMap.putIfAbsent(id, new Object());
}

//the request method
bar(long id){
    maintainLockObjects(id);

    synchronized(lockMap.get(id)){
        //logic here
    }
}

看看ClassLoader.getClassLoadingLock:

Returns the lock object for class loading operations. For backward compatibility, the default implementation of this method behaves as follows. If this ClassLoader object is registered as parallel capable, the method returns a dedicated object associated with the specified class name. Otherwise, the method returns this ClassLoader object.

它的实现代码你可能很熟悉:

protected Object getClassLoadingLock(String className) {
    Object lock = this;
    if (parallelLockMap != null) {
        Object newLock = new Object();
        lock = parallelLockMap.putIfAbsent(className, newLock);
        if (lock == null) {
            lock = newLock;
        }
    }
    return lock;
}

第一个 null 检查仅用于提到的向后兼容性。因此,除此之外,此大量使用的代码与您的方法之间的唯一区别是此代码避免在之后调用 get,因为 putIfAbsent 已经 returns 旧对象(如果有的话)。

所以简单的答案,它有效,而且这种模式也在 Oracle 的 JRE 实现的一个非常关键的部分中得到证明。