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));
}
}
Baurzhan Konurbayev
Level 40
the first test case is not passing
Under discussion
Comments
- Popular
- New
- Old
You must be signed in to leave a comment
This page doesn't have any comments yet