Search code examples
javaconstructorblocking

Calling a blocking method from Constructor - Java


I would like to know if it is a bad idea to call a blocking method from within constructor itself.

I am curious to know if we have any guidelines/rules in such a scenario, that we should never call blocking methods in Constructor.

Basically I am trying to do this:

class A
{
    // Many instance variables that is to be initialized on instantiaion
    String tempVar = null;

    public A()
    {
        // Initialize all the instance variables
        tempVar=objectClassB.**callBlockingMethod**(); // this method call would return 
                                                       // some data from ClassB Object
    }

    public static void main(String args ...)
    {
        A a = new A();
        // Or should I call the blocking method call only after instantiation according
        // to any guidelines of Java pertaining to performance ?

        // IMPORTANT: It's only when the blocked method returns value , should the main
        // thread proceed as the object 'a' would be sent for further processing
    }
}

PS: Eh ,I'm sorry if my question sounds very basic.


Solution

  • I thought its better you can create one method like connect () inside the class A. After creating object you can call like

    A a = new A() A.connect()

    Inside connect method you define the blocking method StreamConnection con=notifier.acceptAndOpen() .....

    if your blocking call doesn't return in specified time period, you consider some mechanism to recover this scenario