title: How to read unique elements from array per thread?
body: <p>I have an object based on array, which implements the following interface:</p>
  
  <pre><code>public interface PairSupplier&lt;Q, E&gt; {
       public int size();
  
       public Pair&lt;Q, E&gt; get(int index);
  }
  </code></pre>
  
  <p>I would like to create a specific iterator over it: </p>
  
  <pre><code>public boolean hasNext(){
       return true;
  }
  
  public Pair&lt;Q, E&gt; next(){
       //some magic
  }
  </code></pre>
  
  <p>In method <strong>next</strong> I would like to return some element from <strong>PairSupplier</strong>. </p>
  
  <p>This element should be unique for thread, other threads should not have this element. </p>
  
  <p>Since PairSupplier has a final size, this situation is not always possible, but I would like to approach it. </p>
  
  <p>The <strong>order</strong> of elements doesn't matter, thread can take same element at a <strong>different</strong> time. </p>
  
  <p><strong>Example</strong>:   <code>2 Threads</code>, <code>5 elements</code> - <strong><code>{1,2,3,4,5}</code></strong></p>
  
  <pre><code>Thread 1  | Thread 2
     1           2
     3           4
     5           1
     3           2
     4           5
  </code></pre>
  
  <p><strong>My solution</strong>:</p>
  
  <p>I create AtomicInteger index, which I increment on every <strong>next</strong> call.</p>
  
  <pre><code>PairSupplier pairs;
  AtomicInteger index;
  
  public boolean hasNext(){
       return true;
  }
  
  public Pair&lt;Q, E&gt; next(){
       int position = index.incrementAndGet() % pairs.size;
       if (position &lt; 0) {
            position *= -1;
            position = pairs.size - position;
       }
       return pairs.get(position);
  }
  </code></pre>
  
  <p><strong>pairs</strong> and <strong>index</strong> are shared among all threads.</p>
  
  <p>I found this solution not scalable (because all threads go for increment), maybe someone have better ideas?</p>
  
  <p>This iterator will be used by <strong>50-1000 threads</strong>.</p>