2013-07-02 43 views
2

我想知道從構造函數本身中調用阻塞方法是否壞主意。從構造函數調用阻塞方法 - Java

我很想知道在這種情況下是否有任何指導原則/規則,我們不應該在構造函數中調用阻塞方法。

基本上我想這樣做:

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:嗯,我很抱歉,如果我的問題聽起來很基本的。

+3

請在此處定義「阻塞」 - 您是否期待它花費不確定的時間?通常構造函數應該相當簡單 - 例如,您不希望永遠循環監聽TCP連接,但可以進行一些方法調用。 –

+0

嗨@JonSkeet,非常感謝您的快速回復。 是的,我的意思是「阻塞」與您提到的完全相同。 我想通過藍牙偵聽傳入連接,並通過阻塞方法調用的返回值初始化「連接」變量。 要非常清楚,我試圖做到這一點: StreamConnection con = notifier.acceptAndOpen(); - >在構造函數 //其中通告程序== StreamConnectionNotifier類型 – Chandru

回答

1

我想它更好,你可以創建一個像一個方法連接()的A類創建對象後,在裏面可以調用諸如

一個一個新= A() A.connect()

內部連接方法您定義的阻塞方法 的StreamConnection CON = notifier.acceptAndOpen() .....

如果您阻塞調用不會在指定時間內返回,你考慮一些機制來恢復這個場景

+0

@「Jojo John」是的,很確定謝謝。所以我明白,在調用cosntructor的時候會有一些擔心/性能問題。 將按照您的建議實施,並使用Some Threads處理它們。 – Chandru