Collections.SynchronizedList实现 - 同步方法与互斥锁

问题描述 投票:0回答:1

java.util.Collections.SynchronizedList中方法的实现是在互斥锁上使用同步。鉴于在所有方法中,完整的方法体在同步块下,为什么不能将它写为同步方法?

基本上:

public boolean doSomething(Collection<?> coll) {
    synchronized (mutex) {return c.doSomething(coll);}
}

public synchronized boolean doSomething(Collection<?> coll) {
    return c.doSomething(coll);
}

我没有扫描所有的类,但可能是因为某些方法需要部分同步(即不是整个方法体),并且由于它们扩展了相同的基类(SynchronizedCollection),实现恰好在使用互斥锁具有更好的控制能力。那是对的吗?对于这种实施选择,还有其他原因,如性能吗?

java multithreading collections concurrency
1个回答
2
投票

为什么它不能写成同步方法?

有一个package-private factory method for SynchronizedListcorresponding package-private constructor,它允许使用除列表本身之外的互斥体构建列表。

你不能直接使用它,但在java.util包中会有它的用法。

一个例子是在SynchronizedList.subList

    public List<E> subList(int fromIndex, int toIndex) {
        synchronized (mutex) {
            return new SynchronizedList<>(list.subList(fromIndex, toIndex),
                                        mutex);
        }
    }

即,对子列表的访问在父列表上同步,而不是子列表。

另一个例子是Vector.subList method

public synchronized List<E> subList(int fromIndex, int toIndex) {
  return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                                      this);
}

即,对子列表的访问在Vector上同步,而不是子列表。

© www.soinside.com 2019 - 2024. All rights reserved.