Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting content of a collection in a thread-safe manner
    text
    copied!<p>I would like to <strong>read</strong> the content of a java Collection in a multi-threaded way. There have been a lot of questions here with the same context, but none on the specific read point.</p> <p>I have a collection of integer. I just want several threads to iterate over it, each thread pulling one integer at a time. I want to make sure all the collection is iterated, and that no integer is pulled twice by two different threads. </p> <p>Frankly, I do not know what works. I know that Iterators are not thread-safe, but when it comes to read only I do not know. I did some test to try and get thread faults, but did not reach 100% certainty:</p> <pre class="lang-java prettyprint-override"><code>int imax = 500; Collection&lt;Integer&gt; li = new ArrayList&lt;Integer&gt;(imax); for (int i = 0; i &lt; imax; i++) { li.add(i); } final Iterator&lt;Integer&gt; it = li.iterator(); Thread[] threads = new Thread[20]; for (int i = 0; i &lt; threads.length; i++) { threads[i] = new Thread("Thread " + i) { @Override public void run() { while(it.hasNext()) { System.out.println(it.next()); } } }; } for (int ithread = 0; ithread &lt; threads.length; ++ithread) { threads[ithread].setPriority(Thread.NORM_PRIORITY); threads[ithread].start(); } try { for (int ithread = 0; ithread &lt; threads.length; ++ithread) threads[ithread].join(); } catch (InterruptedException ie) { throw new RuntimeException(ie); } </code></pre> <p>EDIT: In the real use-case, each of this integer is used to start an intensive work, such as finding whether it is prime. </p> <p>The above example pulls the list of integer without duplicates or misses, but I do not know whether it is by chance.</p> <p>Using a HashSet instead of an ArrayList works as well, but again, it might be by chance.</p> <p>How do you do in practice if you have a general collection (not necessarily a list) and need to pull its content in multithreaded fashion?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload