by BehindJava

How to make your collections thread-safe?

Home » java » How to make your collections thread-safe?

In this tutorial we are going to learn about making our collections as thread-safe.

Thread safe collections can be deceiving.

  • The problem is there are several levels of thread safe collections. I find that when most people say thread safe collection what they really mean “a collection that will not be corrupted when modified and accessed from multiple threads”

But if building a data thread safe list is so easy, why doesn’t Microsoft add these standard collections in the framework?

ThreadSafeList is a virtually unusable class because the design leads you down the path to bad code.

The flaws in this design are not apparent until you examine how lists are commonly used. For example, take the following code which attempts to grab the first element out of the list if there is one.

static int GetFirstOrDefault(ThreadSafeList<int> list) {
    if (list.Count > 0) {
        return list[0];
    }
    return 0; }

This code is a classic race condition. Consider the case where there is only one > element in the list. If another thread removes that element in between the if statement and the return statement, the return statement will throw an exception because it’s trying to access an invalid index in the list. Even though ThreadSafeList is data thread safe, there is nothing guaranteeing the validity of a return value of one call across the next call to the same object