This content has been marked as final. Show 2 replies
897882 wrote: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).
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.
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.