简体   繁体   English

当foreach添加元素时,scala MutableList为什么不抛出异常

[英]scala MutableList when foreach add element why not throw Exception

when I try scala list, I found a question. 当我尝试scala列表时,我发现了一个问题。 when I use a MutableList, just want to try append a element in foreach (I know this is a bad operation): 当我使用MutableList时,只想尝试在foreach中附加一个元素(我知道这是一个错误的操作):

import scala.collection.mutable.MutableList
val tts = MutableList("Hello World~")
tts.foreach { t => 
  tts += "Hello World~"
  println(t)
}

Console Output: 控制台输出:

Hello World~
Hello World~

My question is why the above code not throw a ConcurrentModificationException or output normaly? 我的问题是,为什么上面的代码不抛出ConcurrentModificationException或正常输出?

Throwing the ConcurrentModificationException on modifications during iteration is generally called fail-fast semantics. 在迭代期间将ConcurrentModificationException抛出修改时,通常称为快速失败语义。 Scala collection classes normally do not throw ConcurrentModificationException s because: Scala集合类通常不会抛出ConcurrentModificationException因为:

  • fail-fast complicates the implementation of the iterator 快速失败使迭代器的实现复杂化
  • fail-fast usually slows down the iterator implementation 故障快速通常会减慢迭代器的实现
  • fail-fast is hard to guarantee in all cases (even Java classes do not guarantee it and do it on a best-effort basis ) 在所有情况下都很难保证快速失败(即使Java类也不保证并且会尽力而为
  • fail-fast is even harder to ensure in multithreaded code 在多线程代码中更难确保快速故障转移

Because of this reasons, Scala just documents that concurrent modifications are not allowed, rather than striving for fail-fast and ending up with a leaky abstraction. 由于这个原因,Scala仅记录了不允许进行并发修改,而不是努力实现快速失败并以泄漏抽象告终。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM