Question

i have a list of string(tagList) which need to shared among multiple threads for reading, so i create a unmodifiable version of it and pass it to threads, i m not sure if it's thread safe, since threads only read that list so i guess it should be ok?

also when i pass that unmodifialble list to the threads, does it pass a single copy and shared by threads or does it create multiple copy and pass one copy to each thread?

here is my code:

final List<String> tList = Collections.unmodifiableList(tagList);
List<Future<Void>> calls = new ArrayList<Future<Void>>();

FileStatus[] fsta = _fileSystem.listStatus(p);      
for (FileStatus sta : fsta) {
    final Path path = new Path(sta.getPath(), "data.txt");
    if (!_fileSystem.exists(path)) {        
        continue;
    }
    else {
        calls.add(_exec.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                filterData(path, tList);
                return null;
            }
        }));
    }
}
Was it helpful?

Solution

This completely depends on whether underlying list is thread safe on read operations. Unmodifiable list just passes all read calls, such as size (), get (int) etc to underlying list without additional synchronization.

Imagine, for example, implementation of List which caches hash code instead of calculating it each time it is needed. For such implementation, hashCode () method is actually not read-only, because it may modify internally cached hash code value.

Another example is a flavor of LinkedList which caches reference to last accessed entry together with its index, so further attempts to access nearby elements will be performed much faster. For such implementation, method get (int) will be not read-only because it updates cached reference and index, and thus will probably be not thread safe.

OTHER TIPS

It is thread safe (since it can't be modified). It passes the same copy around.

However, the wrapped List (tagList) is still NOT thread safe. You must not modify the wrapped List while it's being shared. The only reason the list returned by unmodifiableList() is safe is because modifications are not allowed through it to the wrapped List.

As you say that the list is unmodifialble; hence it will be thread safe.

When you pass an object you actually pass the reference to the object (and not the actual object). As there is a single copy and its not getting modified so it will remain thread safe.

Just one caution; never access tagList directly. Access it always through wrapped unmodifiable collection named as tList. This can be achieved if you encapsulate it properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top