Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is unmodifiableList thread safe?

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;
            }
        }));
    }
}
like image 988
user468587 Avatar asked Feb 05 '13 17:02

user468587


1 Answers

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.

like image 173
Mikhail Vladimirov Avatar answered Sep 28 '22 19:09

Mikhail Vladimirov