从远程服务 android 创建单例类
我创建了一个远程服务。在此远程服务中,我正在创建一个单例对象。一旦创建,该对象应该一直保留到其垃圾被收集为止。现在,当我从单例类内部访问这个对象时,我得到了正确的对象。但是当我从外部类访问它时,它的单例对象为空,并且我的类再次被创建。我丢失了所有初始化的对象。
我的单例类如下
class myFactory {
private static myFactory instance;
private myFactory(){
}
public static myFactory getInstance(){
if(instance == null) {
instance = new myFactory();
}
return instance;
}
}
我尝试覆盖单例类中的finalize以检查对象是否被垃圾收集,但它没有出现在该函数中。
在连接工厂对象之外,无论我访问这个单例对象,我都会得到 null,因此创建新对象>我做错了什么?
I have created a remote service. In this remote service i am creating a singleton object. Once created this object should stay till its garbage collected. Now when i access this object from inside the singleton class i getting correct object. but when i am accessing it from outside class it singleton object is null and my class is getting created again. I am loosing all the initialised object.
my singleton class is as follows
class myFactory {
private static myFactory instance;
private myFactory(){
}
public static myFactory getInstance(){
if(instance == null) {
instance = new myFactory();
}
return instance;
}
}
I tried to overide finalize in singleton class to check if the object gets garbage collected but it doesnt come in that function.
Outside the connection factory object where ever i access this singleton object i am getting null and therefore new object is created > what am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个单例,我不明白为什么它不起作用。但我猜你正在尝试在某种 IPC 上下文中使用 Singleton,这将是问题所在(因为远程服务据我所知总是一个新线程)。
问题是:为什么需要单例......没有更好的解决方案吗?我不知道你的整个服务结构,但也许在绑定到服务时获取工厂的实例是有意义的。
如果您能提供更多信息,它可能会有所帮助
This is a Singleton, and I don't see why it shouldn't work. But I guess you are trying to use the Singleton in some kind of IPC-context, that would be the problem (since a remote service is afaik always a new Thread).
Question is: Why do you need a Singleton...isn't there a nicer solution? I don't know your whole Service structure, but maybe it makes sense to get the instance of the Factory while binding to the service.
It could help, if you can give more information