为什么CopyOnWriteArrayList中只能有一个写入操作?

huangapple go评论77阅读模式
英文:

Why can there be just one write in CopyOnWriteArrayList?

问题

CopyOnWriteArrayList做得很好。我可以同时从多个线程读取,但只能从一个线程进行更新。它的工作方式是,写操作使用数组的单独副本,更新信息并将其设置回原始数组。

问题是:由于写操作使用单独的副本,它们为什么不能并行执行?由于它们现在在不同的数组中工作,就不会有任何干扰。所以无论谁先写,它都会将这些新的更新设置到原始数组中。那么为什么Java只允许一个写操作?

我是否在这里漏掉了什么,为什么只能有一个线程进行写操作?

英文:

CopyOnWriteArrayList did a good job. I can read from multiple threads at same time, but I can update from 1 thread. The way it works is that write uses separate copy of array, update info and set it back to original array.

Question is: Since write operations use separate copy, how they can't do it parallely? Since they work in different arrays now, there won't be any interference. So whoever writes 1st, it sets those new updates to an original array. So why does Java allow only one write?

Am I missing something here why can only 1 thread write?

答案1

得分: 2

如果两个线程同时向CopyOnWriteArrayList添加元素,则我们期望这两个元素随后都存在于列表中。由于竞争条件导致元素丢失并不是CopyOnWriteArrayList的设计者和用户所希望的。

进一步展开:如果有两个线程,它们执行以下操作:

线程1:list.add("A");

线程2:list.add("B");

期望的最终结果是,list 包含了A和B,即使不一定是按照这个顺序。

英文:

If two threads add an element to a CopyOnWriteArrayList at the same time, we expect both elements to be present in the list afterwards. Elements getting lost due to race conditions is not what the designers and users of CopyOnWriteArrayList want.

To expand: if you have two threads, and they do the following operations:

thread 1: list.add("A");

thread 2: list.add("B");

The expected end result is that list contains both A and B, even if not necessarily in that order.

huangapple
  • 本文由 发表于 2020年8月21日 20:11:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63522715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定