This discussion is archived
2 Replies Latest reply: Jul 19, 2012 1:37 PM by jtahlborn RSS

Synchronization and visibility

820507 Newbie
Currently Being Moderated
Hi,

I am trying to wrap my head around the concept of multi-threading and visibility. Let's say I know the access to a specific object will be sequential, but from different threads:
public class MyNameList  {
   private ArrayList<String> nameList = new ArrayList<String>();

   public void addName(String name) {
      getNameList().add(name);
   }

   public ArrayList<String> getNameList() {
      return nameList;
   }
}
If I call addName() from thread1 and addName() from thread2, what do I need to synchronize to preserve visibility? Is it enough to synchronize getNameList(), or do I have to synchronize addName()?
  • 1. Re: Synchronization and visibility
    900885 Newbie
    Currently Being Moderated
    By sequential do you mean that at any given time only ONE thread will ever try to access getNameList AND addName? If that is the case, then you don't need to synchronize anything.
  • 2. Re: Synchronization and visibility
    jtahlborn Expert
    Currently Being Moderated
    897882 wrote:
    By sequential do you mean that at any given time only ONE thread will ever try to access getNameList AND addName? If that is the case, then you don't need to synchronize anything.
    no, that's no true. synchronization establishes both mutual exclusion and memory visibility. just accessing the object at different times will not establish visibility between the 2 threads, thus the second thread could see the nameList in any manner of inconsistent (or empty) state. you must establish a "happens before" relationship between the method calls in order for the code to work correctly. synchronizing the 2 methods would certainly work, however you are exposing yourself to trouble since you pass the List outside of the MyNameList class (thus 1 thread could be reading it while a new thread calls add() and things really get messed up).

    if you really want to pass around the internal List, you should most likely make that list thread-safe (e.g. wrap it using Collections.synchronizedList() or use a concurrent implementation). there are other ways to make the code thread-safe, but this is a simple solution.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points