Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

please help, about synchronized block

 
Zu Ji Yun
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I miss understand the use of synchronized block after I saw the following example(from J2SE 1.5 Docs),




I think an object is thread safe in the synchronized block that declared as synchronized(object), but after I saw the example, I think I am wrong!
Because if I am right, then we no need to call Collections.synchronizedCollection(myCollection), I think the following code is correct before I read the example I mentioned,



Why we need call Collections.synchronizedCollection() with myCollection even we define the synchronized block?

I holp you understand what I means with my poor english!

thanks!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct - if you're iterating the collection, the synchronizedCollection() call doesn't help you at all. It's possible that synchronizedCollection() may benefit if there is more code (not shown) which accesses this collection. However in general I find all the Collections.synchronizedXXX() methods to be of very limited use, since usually you need additional explicit synchronization for at least some of the code. At that point I would prefer to explicitly synchronize all the code that accesses the collection. Otherwise someone may well think that their code is "thread safe" just because it uses a synchronizedXXX() method, when actually it needs synchronization at a higher level. (For example, synchronization covering multiple method calls, as you did for the iterator.) I think it's better for people to see exactly where the beginning and end of each synchronized block occurs, and adjust those positions as necessary.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At that point I would prefer to explicitly synchronize all the code that accesses the collection.


Excellent, the only way to be really safe. And one way you can be sure is to hide the collection, private inside some class that has the only code that directly touches the collection. Then it's pretty easy to inspect the code for any unsynchronized access.

Once you have a public getCollection() method you lose control and don't know whether some new code is going to forget to synchronize.

BTW: Welcome to the ranch with a first post!
[ June 28, 2006: Message edited by: Stan James ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!