aspose file tools*
The moose likes Java in General and the fly likes wait() from within static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "wait() from within static method" Watch "wait() from within static method" New topic
Author

wait() from within static method

Mike Rad
Greenhorn

Joined: Nov 07, 2008
Posts: 2
HI,

I know that you can't call wait() from a static method, but what if you need to block your thread in a static method until some condition is met?

For example, lets assume you have a static getObject() method that returns some object instance but you want it to block if the makeObject() method hasn't been called yet to make the object?

public final class singleton{
private static singleton inst = null;
private singleton(){}
public static synchronized singleton getSingleton(){
if(null==inst){
// i want to block until it is not null without using a loop
}
return inst;
}

public static synchronized singleton makeSingleton(){
if(null==inst){
inst = new singleton();
}
return inst;
}
}
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18977
    
  40

synchronized static methods use the Class object to synchronize on. So, if you want to wait on the same object, you can use...

singleton.class.wait();


Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Mike Rad
Greenhorn

Joined: Nov 07, 2008
Posts: 2
Ahhhh, yes, using the class object works just fine. Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: wait() from within static method