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.
Output: Synchronized methods test: start display: end display: start update: end update:
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 ]
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 ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Jun 19, 2008
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.