Can you mix Synchronize and Lock API
I was recently trying out mixing both synchronize and manual lock using lock apis. Interestingly, Synchronize locks the object but when you use Reentrant lock using API, it locks up the object too.
Its generally not recommended to mix as Synchronize is a implicit way of locking. But you have to be extra careful when dealing this way.
Refer to API : Docs
Snippet I tried.
Snippet I tried.
import java.util.concurrent.locks.ReentrantLock;
public class Threads {
static X x = new X();
public static void main(String arg[]) {
Thread tA = new Thread(new Runnable() {
public void run(){
x.addA();
}
},"T1" );
tA.start();
Thread tB = new Thread(new Runnable() {
public void run(){
x.addB();
}
},"T2");
tB.start();
Thread tC = new Thread(new Runnable() {
public void run(){
x.callMe();
}
},"T3");
tC.start();
}
}
class X {
private final ReentrantLock lock = new ReentrantLock();
public void addA() {
synchronized(this) {
System.out.println("A :"+Thread.holdsLock(this));
System.out.println(lock.tryLock());
}
}
public void addB() {
System.out.println("B :"+Thread.holdsLock(this));
}
public void callMe() {
System.out.println("C :"+Thread.holdsLock(this));
}
}
No comments :
Post a Comment