File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronized

 
Saibabaa Pragada
Ranch Hand
Posts: 162
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, This is from ExamLab regarding synchronized context. I am trying to understand the difference between the Option 1, Option 2 and Option 3 because I get the same output all the time. I was told that Option1 and Option 3 are exactly same. what is this Option 2 ??
 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
option 2 will cause to synchronize on the String literal x
that will be stored in the String constant pool somewhere as we are not creating a new String

so the block will synchronize on the String literal x

hope this helps

When are you going to take the exam Saibaba?
 
Saibabaa Pragada
Ranch Hand
Posts: 162
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Prasad, I am planning to take the exam in 2 weeks. The more I read, the more I am learning & getting more doubts. Based on your comments, Can I assume that All 3 options will synchronize & give the same output ?
Prasad Kharkar wrote:option 2 will cause to synchronize on the String literal x
that will be stored in the String constant pool somewhere as we are not creating a new String

so the block will synchronize on the String literal x

hope this helps

When are you going to take the exam Saibaba?
 
Mohamed Sanaulla
Saloon Keeper
Pie
Posts: 3159
33
Google App Engine Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Option 1 and Option 3 are similar because- In both the threads- the same instance of Runnable(XSync) is being used- So there is no difference in synchronizing with "this" or XSync.class. Had the threads been using a different instance of XSync- then Option 1 and Option 3 would be different because synchronizing with "this"- Instance level lock but synchronizing with XSync.class- Class level lock.

And as the String are created in the String pool- So if the same string is being used- It doesn't create the same string each time, instead it reuses the previously created string.

And in the example you have given- Output would be same. But lets see another example: You can change the lines 22-23 as follows:


And then try the three options. You will see that its not Atomic when synchronized on "this".
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic