Dibyajyoti Behera
Dibyajyoti Behera

Reputation: 171

How to use lambda while creating a new Thread?

I have below code for demonstrating a Deadlock situation in Java. I am just trying replacing a Runnable object variable with lambda.

public class DeadLockExample1 {
    public static void main(String[] args)    {
        Shared s1 = new Shared();
        Shared s2 = new Shared();
        Runnable runnable1 = () -> s1.methodOne(s2);
        Runnable runnable2 = () -> s2.methodTwo(s1);

        //below two lines works fine as usual
        new Thread(runnable1).start();
        new Thread(runnable2).start();

        // if I replace above two lines with below two lines, it runs into stackoverflow error
    //    new Thread(() -> s1.methodOne(s2)).start();
    //    new Thread(() -> s2.methodTwo(s1)).start();
    }

    private static class Shared {
        synchronized void methodOne(Shared s)
        {
            s.methodTwo(this);
        }

        synchronized void methodTwo(Shared s)
        {
            s.methodOne(this);
        }
    }
}

What's going wrong here?

Upvotes: 0

Views: 166

Answers (1)

Gray
Gray

Reputation: 116888

What's going wrong here?

This is a classic race condition. When you say:

new Thread(runnable1).start();

this starts running and calls back and forth between s1.methodOne(...) and s2.methodTwo(...) until it runs out of stack space. All of this happens before the 2nd runnable is started. It takes a little bit of time to start a thread running. If you just put a small sleep in the methods it works.

synchronized void methodOne(Shared s) {
    try { Thread.sleep(10); } catch (InterruptedException e) { /* don't do at home */ }
    s.methodTwo(this);
}

synchronized void methodTwo(Shared s) {
    try { Thread.sleep(10); } catch (InterruptedException e) { /* don't do at home */ }
    s.methodOne(this);
}

The sleeps slow down the running on your threads and the code then demonstrates the deadlock.

Upvotes: 1

Related Questions