יום שישי, 28 ביוני 2019

זהירות! רקורסיה הדדית בין מחלקות (Java)

זה לא מפתיע, גם ביצירה של מחלקות יש להיזהר מ-Deadlock.
נתבונן בקוד הבא:

class A {
    final static B b;
    static {
        System.out.println("In A static block");    
        b = new B();
    }

    A() {
        if (b != null) {
            System.out.println("B is: " + b);
        } else {
            System.out.println("the static block was not completed, "
                    + "inspite of we are in the constructor!!!");
        }
    }
}

class B {
    final static A a;
    static {
        System.out.println("In B static block");   
        a = new A();
    }

    B() {
    }

    @Override
    public String toString() {
        return "I am B";
    }
}