• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of 'static' keyword in sychronized methods

 
jason tan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends,
I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.

But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.

Does it mean, 'static' keyword has anything to do with synchronizaton?
Appreciate your valuable comments.

1. Program1


Output:
Synchronized methods test:
start display:
end display:
start update:
end update:

2. Program2


Output:
Synchronized methods test:
start display:
start update:
end update:
end display:


Edit by mw: Added Code Tags.
[ June 19, 2008: Message edited by: marc weber ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

Each instance has a lock. So if 2 instance methods are synchronized, then callers of those methods are competing for the same object lock.

But each class also has a lock. In this example, the synchronized instance method uses the object lock, but the synchronized static method uses the class lock. Therefore, callers of these methods are not competing for the same lock, so the methods can run "concurrently."

Note that if you made both of these synchronized methods static, then they would again be competing for the same lock -- but it would be the class lock instead of the object lock.
[ June 19, 2008: Message edited by: marc weber ]
 
jason tan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marc,

Thanks for the response. So I understand there are two (and not one) lock for an object. One for its class and another for the instance. I also tried to run the sample by making both of them 'static' and it works exactly as you have mentioned.

Thanks again./ Jason.
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi marc your explaination is very good and precise
I understand your explaination perfectly
Thanks
Regards
Ninad
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic