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

标签 java multithreading collections concurrency

java.util.Collections.SynchronizedList 中方法的实现是在互斥体上使用同步。既然所有的方法中,完整的方法体都在synchronized block 下,为什么不能写成synchronized方法呢?

基本上:

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

对比

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

我没有扫描所有的类,但可能的原因是某些方法需要部分同步(即不是整个方法体),并且由于它们扩展了相同的基类(SynchronizedCollection),所以实现发生了使用互斥体来进行更精细的控制。那是对的吗?或者是否有任何其他原因(例如性能)选择这种实现?

最佳答案

why couldn't it be written as synchronized methods?

有一个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 上同步,而不是在子列表上同步。

关于java - Collections.SynchronizedList 实现 - 同步方法与互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060886/

相关文章:

Java GUI完全丢失

java - 处理关机事件

c++ - std::thread 参数的生命周期

java - AsyncTask 和 Thread 不会在 java/android 应用程序中运行两次

java - 替换 forEach 并添加 collect

java - Android 编程 HtmlUnit

java - 在 Kafka Consumer 中反序列化 Avro 数据包时出现堆空间问题

multithreading - 如何使用 Node.js 创建多线程应用程序,访问 LevelDB?

c# - 构建通用集合类

java - 当 compareto 返回 0 时理解 TreeSet