• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronizing on an object

 
Santiago Bravo
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic