aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronized" Watch "Synchronized" New topic
Author

Synchronized

Saibabaa Pragada
Ranch Hand

Joined: Oct 24, 2010
Posts: 162
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

Joined: Mar 07, 2010
Posts: 440

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?

SCJP 6 [86%] June 30th, 2010
OCPWCD [84%] March 26th, 2012
OCEJPAD [83%] September 6th, 2014
If you find any post useful, click the "plus one" sign on the right
Saibabaa Pragada
Ranch Hand

Joined: Oct 24, 2010
Posts: 162
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

Joined: Sep 08, 2007
Posts: 3071
    
  33

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".


Mohamed Sanaulla | My Blog
 
 
subject: Synchronized