• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronize question

 
Akash Singh
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from Max book. Faq on Threading page no 137.
Q: What happens when one method synchronizes on a member method, and another
synchronizes on this memeber variable, and two have to inertact :
A: Then you are acquring two locks on tho distinct objects-namly this and the member variable, and it is very important to be careful. Otherwise, you are openeing the door to deadlock.
My question :
I have two cases below, i could not understand, is it case(given below) 1 or 2?
case 1:
public class TestCase1{
//some instance variables
public synchronize void methodA(){
// some code
}
public void methodB(){
synchronize(this){
//some code
}
//some code
}
}
case 2:
public class TestB{
private Vector container;
public void methodA(){
synchronize(container){
// some code
}
//some code
}
public void methodB(){
synchronize(this){
//some code
}
//some code
}
Or, some other case which i am missing.
Regards,
Akash.
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 12007
215
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Akash,
It would be easier to read your code if you put it between [code] and [/code] tags.
Case two has the potential for concern that Max was talking about. In itself, there is no problem with the code you have provided. But if either method refered to the other method, then you have the potential for deadlock.
Here is an expansion of your code, deliberately designed to cause the deadlock. Can you see how this happened?

Regards, Andrew
 
Akash Singh
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Andrew. Yes, this may cause dead lock.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic