开发者

Can we use wait() method on constructors? Java

Can we use wait() method on constructors? I have a constructor m开发者_如何学JAVAethod in which i call some other initializers methods and after the methods for gui. But it seams that it loads gui before the first methods. So it gives errors to objects that haven't been initialized. I tried to use wait() before gui's calling but there is an IllegalMonitorStateException error as it's not in a synchronized block.

Trying to do sth like that:

dice = new Dice();
this.generateBoard();
this.generateCells();

this.wait(200,100);   //otherwise??
//GUI
board = new GUI(this);


As you noted, you should call wait() within a synchronized block. And synchronizing by default means you lock on this, thus in effect publishing the object before it is fully constructed - a very bad idea.

But - as @Jon pointed out - even if you did explicitly lock on a different object than this, you still needed to publish this prematurely to another thread in order for wait() to make any sense (otherwise who could ever notify() it?). So this scheme smells.

A better alternative would be using a static factory method to construct the object fully, then publish it safely:

class MyClass {
  private MyClass() {
    ...
  }
  public static MyClass createAndPublish() {
    MyClass theInstance = new MyClass();
    // here you can already synchronize on theInstance, call wait() etc.
    return theInstance;
  }
}

Notice that the constructor is declared private to ensure that the only way to create new instances is via createAndPublish():

MyClass newInstance = MyClass.createAndPublish();


Well, you can use wait within a constructor - you'd just have to synchronize on "this" within the constructor:

// I'm not actually recommending this...
synchronized (this) {
    this.wait(...);
}

However, it's not clear what would notify the reference, unless you'd leaked "this" in the constructor to something which was using it in another thread.

It's not at all clear how this is failing to start with to be honest - although I suspect it's to do with leaking "this" at the end of the constructor. Do your initialization methods start extra threads to do their work? It seems to me that you should find out exactly what's going on before you try to fix it - and just pausing for some time seems like a bad idea to me.


Can we use wait() method on constructors?

Not really, as others have pointed out.

But you can split your constructor code into two parts. Do the part that can safely be done before your GUI is created in the constructor. Do the part that has to wait for the GUI to be created in an initialize() method, that can be called after the GUI creation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜