How to make atomic exchange - Scala method?

Problem

I have a code like this

var ls = src.iter.toList
src.iter = ls.iterator

(this is part of the copy constructor of my iterator-wrapper), which reads the original iterator, and in the next line, back. The problem is that these two lines should be atomic (especially if you think that I am changing the source of the copy constructor - I don't like this, but it's good ...).

I read about the Actors, but I don’t see how they fit here - they are more like an asynchronous execution mechanism. I read about Java solutions and used them in Scala, for example: http://naedyr.blogspot.com/2011/03/atomic-scala.html

My question is: what is the way Scala make some operations atomic? I do not want to use any heavy artillery for this, and I also would not want to use some external resources. In other words, something that looks and feels "right."

I like the solution presented in the link above, because this is what I definitely do - link exchange. And if I understand correctly, I would protect only those 2 lines, and another code does not need to be changed! But I will wait for the final answer.

Background

Since every Nth question, instead of the answer, I read "but why are you using ...", here: How to copy an iterator in Scala? :-)

( ), "", . , .

: http://www.ibm.com/developerworks/java/library/j-scala02049/index.html

, , iter. , , .

"", , , Scala, - , .

Paradigmatic, , . , IteratorWrapper - ( , ). , hasNext() next(), . next() (), IteratorWrapper IteratorWrapper, next() ( ). NULL, raw next() , , IteratorWrapper .

, IteratorWrapper.

- , . , , IteratorWrapper ( ).

+5
1

Scala , , ( ). , , ..

, List . , :

class IteratorWrapper[A]( iter: Iterator[A] ) {
  val list = iter.toList

  def iteratorCopy = list.iterator
}

IteratorWrapper . . , . , :

  • Actor
  • STM (akka ).

: . .

Iterator. - . Scala ​​ , .

- :

//A single iterator producer
class Producer {
  val iterator: Iterator[Foo] = produceIterator(...)
}

//Several consumers, living on different threads
class Consumer( p: Producer ) {
  def consumeIterator = {
    val iteratorCopy = copy( p.iterator ) //BROKEN !!!
    while( iteratorCopy.hasNext ) {
      doSomething( iteratorCopy.next )
    } 
  }  
}

( ) , . , , :

class Producer {
  val lst: List[Foo] = produceIterator(...).toList 
  def iteratorCopy = list.iterator
}

class Consumer( p: Producer ) {
  def consumeIterator = {
    val iteratorCopy = p.iteratorCopy 
    while( iteratorCopy.hasNext ) {
      doSomething( iteratorCopy.next )
    } 
  }  
}

produceIterator . , - , . iteratorCopy , ( ).

, list.iterator . , ( ).

+4

All Articles