File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronizing on an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronizing on an object" Watch "Synchronizing on an object" New topic
Author

Synchronizing on an object

Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
This is not really a problem that im facing, its more of what I have come across while doing questions on synchronization.

The following code (taken from a whizlabs question but I have modified it):


Will give the result:

Current Thread is A
Current Thread is A
Current Thread is B
Current Thread is B

OR

Current Thread is B
Current Thread is B
Current Thread is A
Current Thread is A

As Line1 declares a String object which is shared by any ThreadTest object. If I changed Line1 to be:



The output would be unpredictable as each ThreadTest object gets its own String object. If the Line1 declaration was static then the object
is shared by each ThreadTest object so the output can be predicted.

Now if the String object was local - i.e declared in the run() will that make a difference? Well I have found that the results are the same as above.

Creating a whole new string object will cause an upredicatble output while a string object which is in the pool of strings will give a predictable
output.


Am I on the right track?



Thanks


Santiago
My Path to SCJP Certification My Path to SCWCD Certification
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231
Now if the String object was local - i.e declared in the run() will that make a difference? Well I have found that the results are the same as above.


An object is always created on the heap even if it is created within a method.

In the above case, since you are creating a new object using new String("hello") it does not matter where you are creating from, if it is not static it will have a separate copy for every instance.

Being separate objects, implies they have separate locks, hence two threads synchronizing on different locks implies unpredictability in the results.

And of course, String s = "hello"; being a string literal implies a single memory location shared by all the threads, hence a single lock.


thanks
Harvinder
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronizing on an object