Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java LinkedList be read in multiple-threads safely?

Tags:

java

I would like multiple threads to iterate through the elements in a LinkedList. I do not need to write into the LinkedList. Is it safe to do so? Or do I need a synchronized list to make it work?

Thank you!


1 Answers

They can do this safely, PROVIDED THAT:

  • they synchronize with (all of) the threads that have written the list BEFORE they start the iterations, and
  • no threads modify the list during the iterations.

The first point is necessary, because unless there is proper synchronization before you start, there is a possibility that one of the "writing" threads has unflushed changes for the list data structures in local cache memory or registers, or one of the reading threads has stale list state in its cache or registers.

(This is one of those cases where a solid understanding of the Java memory model is needed to know whether the scenario is truly thread-safe.)


Or do I need a synchronized list to make it work

You don't necessarily need to go that far. All you need to do is to ensure that there is a "happens-before" relationship at the appropriate point, and there are a variety of ways to achieve that. For instance, if the list is created and written by the writer thread, and the writer then passes the list to the reader thread objects before calling start() on them.

like image 176
Stephen C Avatar answered Oct 20 '25 17:10

Stephen C