john
john

Reputation: 707

Is it safe to loop over the same List simultaneously?

I have a list

testList= new ArrayList<String>(); // gets initialized once at the very beginning init(). This list never changes. It's static and final. 

I have a static method that checks if an input value is in this List :

public static boolean isInList (String var1)
            throws InterruptedException  {

        boolean in = false;

        for (String s : testList) {

            if (s.equals(var1))
            {
                in = true;
                break;
            }
        } 

        return in;
    } 

I have a lot of threads that use this method concurrently and check if a certain value is in this list. It seems to work fine. However, I'm not sure if this is safe. Am I doing this correctly? Is it thread safe?

Upvotes: 0

Views: 72

Answers (3)

Jim Garrison
Jim Garrison

Reputation: 86764

It is thread-safe as long as no thread is modifying the list while other threads are reading it.

If you are using iterators over the list, they will "fail-fast" (as in throw ConcurrentModificationException) if the list is modified under them. Other methods of accessing (i.e. get(n)) won't throw an exception but may return unexpected results.

This is all covered in great detail in the Javadoc for List and ArrayList, which you should study carefully.

Upvotes: 3

MC Emperor
MC Emperor

Reputation: 22977

As long as you can guarantee that no one is writing to the list, it's safe.

Note that even if the list is static and final, the code itself doesn't guarantee that the list is never modified. I recommend using Collections.unmodifiableList() instead, because it guarantees that no element is ever added to or removed from the list.


By the way, you can rewrite your code to this:

public static boolean isInList(String var1) {
    for (String s : testList) {
        if (Objects.equals(s, var1)) {
            return true;
        }
    } 
    return false;
}

or just

testList.contains(var1);

Upvotes: 0

Avihoo Mamka
Avihoo Mamka

Reputation: 4786

ArrayList is not a thread safe object. It may works for you now, but in general, when working with threads, you should make sure you're using thread-safe objects that will work with your threads as you expect.

You can use Collections.synchronizedList()

testList = Collections.synchronizedList(new ArrayList<String>());

Upvotes: 2

Related Questions