2

I am thread newbie and am currently going through the thread synchronization chapter. I have a question regarding one scenario in thread locking

Here is what I know:

1: When I put a instance lock in a instance method(i.e.)

private Object lock1= new Object();
private Object lock2 = new Object();
void f1(){
    synchronized (lock1) {

    }
}
void f2(){
    synchronized (lock2 ) {

    }
}

void f4(){
    synchronized (lock2 ) {

    }
}
void f3(){
    synchronized (lock1) {

    }
}

Here what will happen is that, if there is object A of a class X being shared by multiple threads, and some thread t1 is executing f1's block, then until t1 comes out f1 block, all the other threads trying to enter function f3,,f1 will be blocked. Same is the case with f2 and f4.

Now in case of static locks, if a class has multiple static methods, and we want individual locking for those methods rather than class locking, we will have multiple static locks. And those locks will determine, what methods will be blocked.

Up until this point everything is fine. Now If put this static locks in a instance method, what will happen, when two thread on the same object try to access that method?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Max
  • 9,100
  • 25
  • 72
  • 109

2 Answers2

4

When you synchronize on static locks in instance methods, only one thread would be able to enter the critical section controlled by that lock, regardless on what instance of the object is is using.

If you make lock1 static, only one thread systemwide would be able to run f1 or f3, even if you make hundreds of instances of class X, because all static members, including objects on which you lock, are shared among all instances of the class.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Always make any fields (lock1, lock2) volatile or final in a concurrent situation. And also, if you synchronize a block of code on a lock, static context or not, only one can thread go through at a time. So one of those two threads will be blocked until the other is done.

tmn
  • 11,121
  • 15
  • 56
  • 112