Java 单例对象在jar中销毁,但在eclipse中工作
我创建了singleton类,并在不同的类中使用这个类对象。这段代码在eclipse中运行良好 但当我制作runnable jar时,它会占用空的hashmap列表,我不知道为什么我的代码 我的单身班Java 单例对象在jar中销毁,但在eclipse中工作,java,eclipse,jar,Java,Eclipse,Jar,我创建了singleton类,并在不同的类中使用这个类对象。这段代码在eclipse中运行良好 但当我制作runnable jar时,它会占用空的hashmap列表,我不知道为什么我的代码 我的单身班 public class PointCalculate { public HashMap<String, Float> calPoint; private static PointCalculate instance; private PointCalculate(){
public class PointCalculate {
public HashMap<String, Float> calPoint;
private static PointCalculate instance;
private PointCalculate(){
calPoint = new HashMap<String, Float>();
}
public static PointCalculate getInstance(){
if(instance==null){
instance = new PointCalculate();
}
return instance;
}
public void calculatePoint(String uid ,float point){
Float ps = instance.calPoint.get(uid);
if(ps==null) {
ps = point;
instance.calPoint.put(uid, ps);
}
else {
ps = point+ps.floatValue();
instance.calPoint.put(uid, ps);
}
}
}
现在我正在传递hashmap
public static void main(String args[]) throws Exception {
PointCalculate obj = PointCalculate.getInstance();
SqlInsertPoint.givePoint(obj.calPoint);
}
但在SqlInsertPoint.givePoint()中,hashmap列表将为空,我不知道为什么如果有人知道,请帮助我
提前感谢此代码有什么问题?在
main
中,您将获得PointCalculate的一个实例,不要将任何点放入其中,并将其传递给givePoint
方法。因为您没有填充HashMap,所以它应该是空的
另一方面,静态单例很难正确,通常应该避免()。在您的具体案例中,不仅PointCalculate
类不是线程安全的,而且它还向全世界公开calPoint
。因此,任何人都可以运行下面的代码并从本质上覆盖您的实例
PointCalculate.getInstance().calPoint=newHashMap()
嗯,我的第一个想法是,你的工厂方法不是线程安全的,所以你不能保证你的对象是单例的。@Aurand请给我一些提示,我没有得到,因为我从来没有在线程中工作过,也没有使用任何线程method@RishiDwivedi在调用SqlInsertPoint.givePoint之前是否调用Exp.setPoint?如果不是,这就是你的问题。Singleton不会在磁盘上自动保存数据。因此,每次处理Singleton对象时(每次程序终止时),您都会丢失它的状态及其在内存中保存的信息。如果需要保存数据,则需要在程序终止之前将其保存到磁盘(使用DB、序列化等)。private final static PointCalculate instance=new PointCalculate();这可能是由于程序执行流的问题。请确保执行是连续的,并且通过添加一些日志只创建了PointCalculate的单个实例。
public static void main(String args[]) throws Exception {
PointCalculate obj = PointCalculate.getInstance();
SqlInsertPoint.givePoint(obj.calPoint);
}