0

I am using Collections.synchronizedList, I have multiple threads building this list. However after it's built I only have a single thread iterating through it. Is the below still imperative in this case?

It is imperative that the user manually synchronize on the returned list when iterating over it:

    List list = Collections.synchronizedList(new ArrayList());
    ...   
    synchronized (list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
    }
PDStat
  • 5,513
  • 10
  • 51
  • 86
  • if all the threads are finished building your list, why you need concurrency control for single thread accessing it? – Shailesh Aswal Oct 04 '19 at 08:50
  • 4
    No. As extra integrity check / measure, you might wrap it in a `Collections.unmodifiableList`, Or for a speedup copy the data to a new list (does not relate to your concern). – Joop Eggen Oct 04 '19 at 08:51
  • That's pretty much my point, was just confirming my suspicions – PDStat Oct 04 '19 at 08:51
  • 1
    If you can ensure single threaded access to the list after it is build, then can't see why iterating without synchronisation would be a problem. Iterator provides direct access to the backing list, just ensure it's not misused – Martin'sRun Oct 04 '19 at 08:56
  • 1
    The warning just says that the _structure_ cannot really deal with an iterator on a change by another thread: the state of the local iterator is not updated. – Joop Eggen Oct 04 '19 at 08:57

1 Answers1

1

After the list is built, and you are certain it no longer needs to be synchronized, create a new unsynchronized list from the old one. No need to continue paying the performance hit.

List< Whatever > list = new ArrayList<>( mySynchList ) ;

If the list will no longer need elements added or dropped or replaced, make it unmodifiable.

List< Whatever > list = 
        Collections.unmodifiableList ( 
            new ArrayList<>( mySynchList ) 
        ) 
;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154