• Post Reply Bookmark Topic Watch Topic
  • New Topic

Concurrent Access Problem  RSS feed

 
Liang Anmian
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got a question regarding concurrent access. Firstly, assume that the program is run on a machine that utilizes preemptive multitasking. Suppose I have a Collection object (be it ArrayList, HashMap etc) in a class. I have one thread that iterates through the collection and do something.

Supposingly while iterating through the collection, the Thread Scheduler preempts the current thread and switch to another thread. In this other thread, changes are made to the collection object (e.g removing elements). So later, when the iteration thread takes over again, there may be errors due to the concurrent access just now.

Can the following prevent the collection from being modified until the iteration thread completes the loop?



If the answer is yes, then I will have to ask, will the above technique work ONLY if the modification methods (e.g add, remove etc) are synchronized?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this will work only if the methods that can mutate the collection are synchronized. Locking an object doesn't help if the object's methods aren't synchronized.

An alternative is to copy the collection before iterating over the copy.
 
Liang Anmian
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Understood. Thank you very much.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java.util.Collections class has methods that will wrap instances of the various Collection classes (Collection, List, Map, Set, SortedMap, SortedSet) with a synchronized proxy.However, it won't help if other objects go through references to "list" instead of "synchList".

As well, a collection class that implements synchronization itself like ConcurrentHashMap can do so much more elegantly. Using two locks -- read and write -- allows many objects to read from the collection concurrently and only locks them out when one is writing to it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!