This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Cannot understand an example from concurreny book.  RSS feed

 
Dmitry Zhuravlev
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gentlemen, please clarify for me an example from java concurrency book which I dont quite understand.

The task is to add a Put-if-absent method to some thread-safe list implementation. Here is class presented by authors of the book:



I cannot grasp the point: why this class is thread-safe?
Indeed, as far as I understand from sources, the list produced by Collections.synchronizedList(...) method uses some internal lock to guard its methods. The putIfAbsent method uses that list as a lock. Consequently, the ListHelper class uses two different locks for updating the internal list and thus the race condition can emerge. I was trying to implement the error I am fuguring here but I failed: when some thread holds the internal list as a lock, other threads cannot modify it. It looks like Collections.synchronizedList(...) uses not internal mutex, but itself as a lock. Whats up?

ps

Also please advise me some good place to browse through JDK source files.
 
Piyush Joshi
Ranch Hand
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dmitry Zhuravlev wrote:
Also please advise me some good place to browse through JDK source files.

You can find JDK source files in the src.zip inside JDK installation folder. Also you can integrate this zip file with eclipse, and view souce in eclipse.
 
Dieter Quickfend
Bartender
Posts: 543
4
Java Netbeans IDE Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29

From the API, I would also say that synchronized list synchronizes on itself, which means that the book is right...
 
Dmitry Zhuravlev
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys, thank you!

Indeed, Collections.synchronizedList lock is an internal object which is... the list itself. I have not checked the init of internal lock in synchronizedList method. Its always good to check the sources first
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was how I remembered it but I double checked the source it defaults to sync on itself, there is a different constructor so you can have a list that doesn't but the code is correct as is.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!