【发布时间】:2012-02-15 09:08:13
【问题描述】:
我有一个类可能会在初始化期间抛出任何运行时异常。我希望这个类是一个单例,因为在内存中保留多个对象的成本很高。我在另一个类中使用该类。
我的用例如下:
- 我必须使用
Controller的单个实例。 -
Parent的每个实例都必须使用相同的Controller实例。 -
Controller构造函数可能会抛出异常。 - 如果实例化失败,我应该 稍后重试实例化。
所以当我尝试对Controller 执行“获取”操作时,我会检查我的控制器实例是否为null,如果是,我会尝试再次实例化它。
以下是我的代码:
class Parent
{
private static volatile Controller controller;
private static final Object lock = new Object();
static
{
try
{
controller = new Controller();
}
catch(Exception ex)
{
controller = null;
}
}
private Controller getController() throws ControllerInstantiationException
{
if(controller == null)
{
synchronized(lock)
{
if(controller == null)
{
try
{
controller = new Controller();
}
catch(Exception ex)
{
controller = null;
throw new ControllerInstatntationException(ex);
}
}
}
}
return controller;
}
//other methods that uses getController()
}
我的问题是,这段代码有问题吗?我在某处读到上面的代码在 JVM 1.4 或更早版本中会出现问题。你能提供参考/解决方案吗?请注意,我之所以问这个问题是因为互联网上有很多关于这个话题的混淆。
谢谢。
【问题讨论】:
-
您使用的是 Java 1.4 或更低版本吗?
标签: java multithreading synchronization