user1634216 user1634216 - 5 months ago 8
Java Question

Changing a Java List Reference While Another Thread Reads It

I couldn't find a clear answer to this question, so apologies if this is nicely answered elsewhere.

Imagine I have something roughly like:

Class SomeClass
{
List<String> strings = new LinkedList<>();


public void updateList(List<String> newStrings) {
strings = newStrings;
}

public List<String> getMatchingStrings(String pattern) {
List<String> matches = new LinkedList<>();
for (String s : strings) {
if (matchesPattern(s, pattern)) { //Assume this just works
matches.add(s);
}
}
return matches;
}

}


Assuming another thread calls
updateList(...)
while some thread is calling
getMatchingStrings()
, will there be a "problem"?

The intended behavior is that the thread currently executing
getMatchingStrings()
will run on the old list, and a subsequent call will run on the updated list.

Any help is appreciated!

Answer

If you mean will there be a runtime exception, the answer is no. The code that iterates over strings will use whatever the reference happens to be when the iterator invokes.

It doesn't matter if the strings reference changes while iterating. Think of it like this,

Iterator<String> i = strings.iterator();
strings = new List<String>();
while (i.hasNext()) {
 ...
 i.next();
}

This code is fine. The object pointed to by strings hasn't changed. We only changed the strings reference to point to somewhere else. The iterator still points to the original object referenced by strings before the assignment.