Loop through list or something else in a unique way
<p>I need to create a method that takes a param as <code>maxValue</code>. And loop through it from 0 but once it uses one index, it must not use it again.</p>

<p><strong>Explanation:</strong></p>

<p>Lets take an example, <code>maxValue</code> is 2000. Now it should go from 0 to 2000 but the start index keeps change by other thread. Like it can be 0 again or it can be 1900 or 1999, can be any number less than <code>maxValue</code>. So it should keep loop from starting index to end and then loop for the rest of items.</p>

<p>Here is what I have tried:</p>

<pre><code>public int i = 0;  //keep changes by other thread

public void DoStuff(int maxValue) {
    HashSet&lt;Integer&gt; valuesSet = new HashSet&lt;Integer&gt;();      

    // fill hashset
    for (int a = 0; a &lt; maxValue; a++)
        valuesSet.add(a);       

    for (; i &lt; maxValue; i++) {
        if (valuesSet.contains(i)) {
            valuesSet.remove(i);
            // SomeMethod(i);
        }

        if (valuesSet.isEmpty())// must check isEmpty first
            break;
        if (i == (maxValue - 1)) // reset i to 0 to use remaining items in hashset
            i = 0;
    }
}
</code></pre>

<p>I haven't tested this code but I can see the problem will come if other thread keep set i to 0 or some less value than <code>maxValue</code> and this loop will go infinite. While it should be something better. Any idea guys?</p>

<p>Edited :<br/>
Deep Example<br/>
<code>i=0</code> and <code>maxValue=2000</code><br/></p>

<p>DoStuff gets called and when <code>i</code> reaches to 100 through loop, <code>i</code> got set by other thread to 1600, loop is keep going but again <code>i</code> got set to 30 by same other thread and then again and again it get set by other thread, Untill all the items in <code>valuesSet</code> get called in <code>SomeMethod(i)</code>. But problem is, if 1 or more item left in <code>valuesSet</code> like 1998 or 1999 and <code>i</code> keep get set to lower like 0 or 10 or 100, the loop has very low chances to break or finish.</p>

<p>What I want is, if once a number(0 to maxValue) get called in <code>SomeMethod</code>, it must not get called again, while the starting number keep changes and <code>SomeMethod</code> must have called with all numbers till maxValue. If <code>SomeMethod</code> get called till maxValue and still numbers left, it should start again with lowest number.</p>
