Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of nested synchronized blocks

Learning about threads and concurrency. Consider the following code:

class A {

  protected final Object lock = new Object();

  public void remove(Object obj){
    synchronized(lock){
      // remove the object
    }
  }

  public void add(Object obj){
    synchronized(lock){
      // add the object
    }
  }
}

This code is thread-safe in the sense that no two different threads can add or remove while one thread is in the process of adding or removing.

Now consider the following sublcass of A:

class B extends A {

  public void update1(Object original, Object newObj){
    remove(original);
    add(original); 
  }

  public void update2(Object original, Object newObj){
    synchronized(lock) {
      remove(original);
      add(newObj);
    }
  }

}

Class B must implement a thread-safe update method. Now, as far as I know update1 is not thread safe because the operation is not atomic, i.e. there is no synchronization between the execution of remove and add (correct me if wrong).

Is update2 the correct way to implement a thread-safe update method? Are there any disadvantages of having nested synchronized blocks over the same lock?

like image 489
fernandohur Avatar asked Jan 09 '23 23:01

fernandohur


1 Answers

Is update2 the correct way to implement a thread-safe update method?

Yes, it is. You have achieved atomicity and you are compatible with callers of the individual add and remove methods.

Are there any disadvantages of having nested synchronized blocks over the same lock?

No, because the locks are reentrant, meaning the second acquisition doesn't do anything more than remember that the lock was acquired once more, so it doesn't get released until two release actions are performed.

like image 200
Marko Topolnik Avatar answered Jan 12 '23 02:01

Marko Topolnik