Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: thread-safe circular iterator

Tags:

scala

What is the correct way to create a thread-safe, infinite circular iterator in scala? It seems that the following is not thread safe (iterating simulataneously from multiple threads on iterator occasionally throws exceptions):

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

How would you correct this to make it thread-safe?

like image 722
joniba Avatar asked Sep 28 '22 17:09

joniba


2 Answers

I've ran into a same question but I think we can do this to be safe as implementation independent as discussed here.

iterator.synchronized(
  iterator.next()
)
like image 69
jk-kim Avatar answered Sep 30 '22 09:09

jk-kim


Just wrap to the Provider. smth like this:

class Iterator2ProviderAdapter[A](iterator: Iterator[A]) {
    def get: A = synchronized(iterator.next())
}
like image 26
Alexandr P Avatar answered Sep 30 '22 11:09

Alexandr P