I have a private LinkedHashMap which is used for reading (only for reading) from different threads:
class foo {
private LinkedHashMap map = ...;
public publicMethodCalledFromDifferentThreads() {
for (Object foo : map) {
...
}
}
}
This implementation is not thread safe and so the for loop can’t behave correctly. I tried to find a solution by myself and the only thing I came up with is the following:
class foo {
private LinkedHashMap map = ...;
private Map.Entry[] mapEntries = map.entrySet().toArray() ...;
public publicMethodCalledFromDifferentThreads() {
for (int i = 0; i < mapEntries.length; i++) {
mapEntries[i]...
...
}
}
}
So in the end I need to have two variables and the iteration gets really complex. What would be the nicest way to do this?
Thanks!
If you are only reading, and the underlying objects are not being modified, both the list and the things in the list, there should be no threading issue.
What issue are you actually experiencing?
I think it’s possible you are modifying your LinkedHashMap somehow.
More over, how are you determining the threads are jumping around? Are you sure you are not just seeing output from the 2 threads intermixed, which would look like jumping around, even though each thread is iterating sequentially? For example if each thread printed its current entry you might see something like
123 12 45 345 6….
which is sequential….