I would like to read the contents of the java collection in a multi-threaded way. There were many questions with the same context, but none of them were indicated at a specific reading point.
I have a set of integers. I just want it to execute multiple threads, with each thread pulling one whole at a time. I want the whole collection to be iterated, and that no whole is pulled twice by two different threads.
Honestly, I do not know what works. I know that Iterators are not thread safe, but when it comes to reading, I don't know. I did some tests to try to get stream errors, but did not reach 100% certainty:
int imax = 500; Collection<Integer> li = new ArrayList<Integer>(imax); for (int i = 0; i < imax; i++) { li.add(i); } final Iterator<Integer> it = li.iterator(); Thread[] threads = new Thread[20]; for (int i = 0; i < 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 < threads.length; ++ithread) { threads[ithread].setPriority(Thread.NORM_PRIORITY); threads[ithread].start(); } try { for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread].join(); } catch (InterruptedException ie) { throw new RuntimeException(ie); }
EDIT: In the actual use case, each of this whole is used to start intensive work, for example, to determine if it is simple.
In the above example, a list of integers is pulled out without duplicates or misses, but I do not know if this is accidental.
Using a HashSet instead of an ArrayList also works, but again, maybe this is random.
How do you do in practice, if you have a common collection (not necessarily a list) and need to pull its contents in a multi-threaded way?
source share