Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait() from within static method

 
Mike Rad
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21197
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mike Rad
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahhhh, yes, using the class object works just fine. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic