• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronize the line or the method?

 
Marilyn de Queiroz
Sheriff
Posts: 9079
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Does this seem silly, or am I just to tired to see the advantage of synchronizing this line? The Hashtable method elements() is already synchronized. But ... it seems to me that someone could change 'e' while the unsynchronized part of this method is looping through the Enumaration.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I think it's probably silly, but it's hard to say for sure without knowing what other code may be doing in the same class. It's true that if other threads have the ability to change the contents of the Hashtable object, then the synchronization shown is insufficient. You'd want to sync around the entire iteration process. You'd also typically sync on the Hashtable itself, not on "this', especially if you otherwise are relying on the Hashtable's own synchronization. Though there's more than one way that can be done I suppose.

I guess it's possible that the code shown serves a purpose if queryHash is a nonfinal instance variable, and if it's possible for other threads to change the reference to refer to a different Hashtable without changing the contents of a preveriously-referenced Hashtable. If that were the case, it would be necessary to sync access to the queryHash reference, but not to the Enumeration. Offhand it seems a bit unlikely that a Hashtable would be used that way, but it is possible. I don't think a more definitive answer is possible without knowing more about the rest of the class containing this code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!