Reputation: 29
I have a question about locks and synchronization.
I have a method that locks object 1, and other method that locks object 2:
private void a(){
synchronized(obj1){
System.out.println("Object 1 being used");
}
System.out.println("Object 1 finished");
}
private void b(){
synchronized(obj2){
System.out.println("Object 2 being used");
}
System.out.println("Object 2 finished");
}
Also I have a third method:
private void c(){
for(int i=0;i<=0;i++){
a();
b();
Thread.sleep(2000);
}
}
I want to hold the lock on both objects, 1 and 2 while the method c
is running, after c
is done, both locks can be released. How can I achieve this? I tried putting them into a for
loop, but the methods a
and b
just start and finish.
Upvotes: 2
Views: 321
Reputation: 96385
Have the c method acquire both locks in nested blocks:
synchronized (obj1) {
synchronized (obj2) {
// c method logic here
}
}
Intrinsic locks are re-entrant so it doesn't matter that methods a and b already acquire them.
If you make more than one method that does this, make sure they acquire the locks in the same order, to avoid deadlocks.
Upvotes: 1