I'm preparing for Java SE 7 Programmer II exam. In one of the mock exams there was an exercise to name from what threading problem does the code suffer. This is the code:
public class Test {
public static void main(String[] args) {
final Counter obj1 = new Counter("obj1");
final Counter obj2 = new Counter("obj2");
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("first");
obj1.display(obj2);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("second");
obj2.display(obj1);
}
}).start();
}
}
class Counter extends Thread {
int i = 10;
String name;
public Counter(String name) {
this.name = name;
}
public synchronized void display(Counter obj) {
try {
Thread.sleep(5);
obj.increment(this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void increment(Counter obj) {
System.out.println(++i);
}
}
They say it is a livelock. I cannot see it. Please can someone explain it in more detail.
I wouldn't qualify this as livelock based on Wikipedia's definition
Though it does fit the definition of deadlock
Your first thread has the lock for
obj1, the second has the lock ofobj2, they then requests the other's lock and block.