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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With