问题代码如下:单例类:
public class WhateverClass{
private static WhateverClass instance; private static Object lockObj = new Object(); private HashMap map; private WhateverClass(){} public static WhateverClass getInstance() throws Exception{
if(instance == null){
synchronized(lockObj){
if(instance == null){
instance = new WhateverClass();
instance.init();
}
}
}
return instance;
} private void init() throws Exception{
map = new HashMap();
map.put("xxx", "xxx");
map.put("xxxx", 1111);
// ..........
} public Something createSomething(){
// some code like:
Object o = map.get("xxx");
// some more code
return something;
}
}调用:
Something st = WhateverClass.getInstance().createSomething();
public class WhateverClass{
private static WhateverClass instance; private static Object lockObj = new Object(); private HashMap map; private WhateverClass(){} public static WhateverClass getInstance() throws Exception{
if(instance == null){
synchronized(lockObj){
if(instance == null){
instance = new WhateverClass();
instance.init();
}
}
}
return instance;
} private void init() throws Exception{
map = new HashMap();
map.put("xxx", "xxx");
map.put("xxxx", 1111);
// ..........
} public Something createSomething(){
// some code like:
Object o = map.get("xxx");
// some more code
return something;
}
}调用:
Something st = WhateverClass.getInstance().createSomething();
解决方案 »
- java 把TextField内容通过按钮事件储存到文本文件中
- 请教大侠,JAVA中如何实现A类调用B类中的main方法
- 关于scjp认证培训!
- 如何将一个标准JavaBean中的数据写入一个XML文件中,要下载新的Java类包吗?
- 关于输入法的切换问题,大虾们过来指点一下。(顶者有分哦)
- 存储过程里面有一个cursor的out型的参数,请问在java中可以拿到吗?
- 请教高手!!!(关于输入输出流)
- 关于JAVAAPPLET的问题
- 谁能告诉我jBuilder4的系列号?不胜感激!
- java多线程问题
- int a = 8,b = 4; int expr = a++%++b*2
- 新开贴,重新描述清楚些-请教一下JAVA关于对象实例调用的问题
感觉这个程序有问题啊
synchronized(lockObj)应该是synchronized(WhateverClass.class)吧
synchronized(lockObj)实现同步时应该用同一个对象上的锁,程序中的lockObj不是同一对象吧!
synchronized(lockObj)应该是synchronized(WhateverClass.class)确实是这里的问题!
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
// some code like:
Object o = map.get("xxx");
// some more code
return something;
}
http://chaoforever.blog.sohu.com/103394321.htmlLZ是不是担心发生这个情况呢~现在的问题越来越脱离生活了..平时接触不到啊..
Object o = map.get("xxx");
行抛出nullpointer异常了。
好像最好的办法就是在定义成员的时候直接初始化了。又有一个问题:
如果构造函数抛出异常了,这个异常是不是无法捕获了?
例如:
public class TestInstance {
public static void main(String[] args) {
try{
A.ins.shit();
}catch(Exception e){
System.out.println("xxxxxxx");
}
}
}
class A{
public static A ins = new A();
private A() {
throw new RuntimeException("shit");
}
public void shit(){
System.out.println("shit");
}
}
private static final WhateverClass instance = new WhateverClass();
static {
try {
instance.init();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
支持!你的用法是想一开始就把map给实例并赋值..为什么不用静态块?