Hi CodeGym,
Stuck with test failure on the first condition.
I was trying to implement a logic where I have 3 threads.
Thread ONE locks o1.
Then thread TWO just calls the method someMethodWithSynchronizedBlocks and locks on o1 (if the order is correct).
Thread THREE will be able to lock o2 and must have thread state equals RUNNABLE.
If order was incorrect then thread TWO must lock on o2 and thread THREE must not be able to lock on o2 and must have state BLOCKED instead.
Any help would be appreciated!
Thanks
package com.codegym.task.task27.task2707;
/*
Determining locking order
*/
public class Solution {
public void someMethodWithSynchronizedBlocks(Object obj1, Object obj2) {
synchronized (obj2) {
synchronized (obj1) {
System.out.println(obj1 + " " + obj2);
}
}
}
public static boolean isLockOrderNormal(final Solution solution, final Object o1, final Object o2) throws Exception {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o1) {
while (true) {}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
solution.someMethodWithSynchronizedBlocks(o1, o2);
while (true) {}
}
});
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o2) {
while (true) {}
}
}
});
thread1.setDaemon(true);
thread1.start();
Thread.sleep(300);
thread2.setDaemon(true);
thread2.start();
Thread.sleep(300);
thread3.setDaemon(true);
thread3.start();
Thread.sleep(300);
// if thread3 could enter o2, the order was correct
return (thread3.getState() == Thread.State.RUNNABLE);
}
public static void main(String[] args) throws Exception {
final Solution solution = new Solution();
final Object o1 = new Object();
final Object o2 = new Object();
System.out.println(isLockOrderNormal(solution, o1, o2));
}
}