Scala: a streaming circular iterator

What's the correct way to create a thread-safe, infinite circular iterator in scala? The following seems to be not thread safe (iterating multiple threads at the same time on an iterator sometimes throws exceptions):

val map = Map(1->"one", 2->"two")
val iterator = Iterator.continually(map).flatten

      

How do you fix this to make it thread safe?

+3


source to share


2 answers


I came across the same question, but I think we can make it safe as implementation independent as discussed here .



iterator.synchronized(
  iterator.next()
)

      

+1


source


Just wrap Supplier. smth like this:



class Iterator2ProviderAdapter[A](iterator: Iterator[A]) {
    def get: A = synchronized(iterator.next())
}

      

0


source







All Articles