I think the code returns the requested value -
I m testing by changing the order of o1 and o2 in the method call here:
solution.someMethodWithSynchronizedBlocks(o1, o2); //true
solution.someMethodWithSynchronizedBlocks(o2, o1); //false
or by changing the order of obj1 and obj2 in the someMethodWithSynchronizedBlocks itself.
Am I misunderstanding the condition? Am I testing the wrong way?
public static boolean isLockOrderNormal(final Solution solution, final Object o1, final Object o2) throws Exception {
final Integer[] check = {0};
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o2){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
check[0]++;
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
solution.someMethodWithSynchronizedBlocks(o1, o2);
}
});
thread1.start();
Thread.sleep(10);
thread2.start();
Thread.sleep(100);
return check[0] == 0 ? true : false;
}
It seems to "succesfully" create a deadlock at the true condition because the check variable isn't changed and the program gets stuck.
However, it doesn't validate.
Any help is appreciated.
Thanks for your time.