Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Overflow Exception in Java

Tags:

java

I am new to Thread. I have created two classes name A and B as follow-

public class A {

    private B b;

    public void setB(B b) {
        this.b = b;
    }

    synchronized void foo() {
        b.foo();
        System.out.println("Hi A");
    }
}

public class B {

    private A a;

    public void setA(A a) {
        this.a = a;
    }

    synchronized void foo() {
        a.foo();
        System.out.println("Hi B");
    }
}

Now i have created two other classes which implements Runnable interface.

public class AThread implements Runnable{
    private A a;
    public AThread(A a){
        this.a = a;
    }
    @Override
    public void run() {
        a.foo();
    }

}

public class BThread implements Runnable {
    private B b;
    public BThread(B a){
        this.b = b;
    }
    @Override
    public void run() {
        b.foo();
    }

}

In main method, i have written the following code-

public static void main(String args[]) {
        A a = new A();
        B b = new B();
        a.setB(b);
        b.setA(a);
        Runnable r1 = new AThread(a);
        Runnable r2 = new BThread(b);
        Thread t1 = new Thread(r1);
        t1.start();

    }

When i am running this code, i got the following exception.

Exception in thread "Thread-0" java.lang.StackOverflowError
    at student.B.foo(B.java:21)
    at student.A.foo(A.java:21)..

Can any one explain what is the route cause of it and how can i solve it?

like image 985
Subhabrata Mondal Avatar asked Aug 13 '26 23:08

Subhabrata Mondal


1 Answers

What did you expect?

You have a foo() method in A calling the foo() method in B that called the foo() method in A, and so on, until the stack overflows.

You can solve it by avoiding circular method calls.

like image 91
Eran Avatar answered Aug 16 '26 17:08

Eran