Why does the following code result in thread contention

I have the following code

public class Test {
Lock lock = new ReentrantLock();

public static void main(String args[]) throws Exception {
    Test t = new Test();
    Second second = t.new Second();
    second.lock = t.lock;
    Thread thread = new Thread(second);
    thread.start();
    Thread.sleep(2000);
    try {
        t.lock.lock();
        System.err.println("got the lock");
    } finally {
        second.shutdown = true;
        t.lock.unlock();
    }
}

private class Second implements Runnable {
    Lock lock;
    volatile boolean shutdown = false;
    int i = 0;

    public void run() {
        while (!shutdown) {
            try {
                lock.lock();
                System.out.println("In second:" + i++);
            } finally {
                lock.unlock();
            }
        }
    }
}

}

I read here that there is a concept of fair and unfair lock, but making locks fair has a big performance impact and nevertheless shouldn't the above code give some fairness to the current thread. While actual execution of the above code, the second thread runs forever (gave way for main thread after 545342 iterations)

Is there something I am doing wrong here? Can anyone explain this behavior?

Answers


Basically without making the lock fair, the second thread is unlocking and managing to reacquire the lock before the first thread gets a chance to do so. After your large number of iterations, it must have been pre-empted between the "unlock" and the "lock", giving your first thread an opportunity to get in and stop it.

Fundamentally though, you simply shouldn't have code like that in the second thread - under what real life situation do you want to repeatedly release and acquire a lock doing no work between the two, beyond checking a flag? (And if you do want to do that, why do you want to require that a "shutting down" thread acquires the same lock in order to set the flag?)


Need Your Help

can't concatenate strings in Python-3

string python-3.x

when running this script in Python-3:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.