我想知道從構造函數本身中調用阻塞方法是否壞主意。從構造函數調用阻塞方法 - 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:嗯,我很抱歉,如果我的問題聽起來很基本的。
請在此處定義「阻塞」 - 您是否期待它花費不確定的時間?通常構造函數應該相當簡單 - 例如,您不希望永遠循環監聽TCP連接,但可以進行一些方法調用。 –
嗨@JonSkeet,非常感謝您的快速回復。 是的,我的意思是「阻塞」與您提到的完全相同。 我想通過藍牙偵聽傳入連接,並通過阻塞方法調用的返回值初始化「連接」變量。 要非常清楚,我試圖做到這一點: StreamConnection con = notifier.acceptAndOpen(); - >在構造函數 //其中通告程序== StreamConnectionNotifier類型 – Chandru