Reputation: 96
I have a class and i make synchronized lock in that class for the same class object For ex.
class Demo{
private Demo obj=new Demo();
synchronized(obj){
//some code here
}
}
then it gives error of stack overflow but i write the same code as
class Demo{
private static Demo obj=new Demo();
synchronized(obj){
//some code here
}
}
Then it works fine so please any one is there to explain me logically what is happening here.
Upvotes: 2
Views: 108
Reputation: 1502196
It's nothing to do with synchronization. You'll have the exact same problem with this code:
class Demo {
private Demo obj=new Demo();
}
You're saying that in order to create an instance of Demo
, you need to create a new instance of Demo
- which will create another new instance of Demo
etc. In your static
version, there's only one static field, initialized once, so you don't get this infinite recursion.
If you want some code to synchronize on itself, you can just use this
:
synchronized(this) {
...
}
Personally I would recommend synchronizing on a separate object which was never exposed though:
public class Demo {
private final Object lock = new Object();
...
// In a method
synchronized(lock) {
...
}
}
It's easier to reason about locks when you know that the only thing which knows about that reference is the Demo
object itself.
Upvotes: 9