[英]Static context saved in Application class and used in a singleton toast builder, does this create a memory leak?
[英]Static singleton class memory leak in android
我有一个扩展我的User对象的静态单例类:
public class TestSingleton extends User{
private static TestSingleton singletonInstance;
private TestSingleton() {
}
public static TestSingleton getObj() {
if (singletonInstance == null) {
singletonInstance = new TestSingleton();
}
return singletonInstance;
}
}
单例的目的是避免在我想在不同的活动中使用我的User对象时创建新实例:
TestSingleton test = new TestSingleton();
test.doSomthing();
并将其写在一行上,并在我的应用程序生命周期中只创建一次实例:
TestSingleton.getObj().doSomthing();
我的问题是:
这种静态Singleton的使用会造成内存泄漏并保持对我使用单例的任何活动的引用吗?
使用安全吗? 还是有更好的解决方案?
这种静态Singleton的使用会造成内存泄漏并保持对我使用单例的任何活动的引用吗?
它不会在99.9%的情况下,
Is it safe to use?
这取决于你的安全意味着什么。 例如,您的实现不是线程安全的。 如果从两个不同的线程调用getObj(),则可能会发生两次实例化TestSingleton。
or there is a better solution?
有一个使用Enum的Singleton模式的实现。 您可以在Effective Java上找到一个示例
如果您只需要一个User
实例,则无需扩展它。 您在TestSingleton
中TestSingleton
只是在User
类中完成。
例如:
public class User{
private static User singletonInstance;
private User() {
}
public static User getObj() {
if (singletonInstance == null) {
singletonInstance = new User();
}
return singletonInstance;
}
}
更新:
用于螺纹安全使用
public synchronized static User getObj() {
if (singletonInstance == null) {
singletonInstance = new User();
}
return singletonInstance;
}
我认为在这种方法中你不需要考虑内存泄漏。
A memory leak may happen when an object is stored in memory but cannot be accessed by the running code
对于单身人士,只创建了一个对象。 并且它仅在首次使用时创建。 没有内存泄漏可能。 只有在要使用多线程时,才必须同步instance(),以便只创建一次对象。
并且99.99%确定不会有任何内存泄漏
是的,单身人士可能会导致内存泄漏,请阅读这篇文章: https : //stackoverflow.com/a/13891253/1028256
在Android生命周期中,可能会重新创建活动,并且可能会发生单例保留对旧活动实例的引用,从而阻止其被垃圾回收。 这意味着如果你保留这样的引用,你应该在单例中,在Activity.onDestroy()上使它们无效
仅供参考,当应用程序被销毁时,单身人士也可能被销毁,因此您无法依赖它。
您可能需要考虑将数据持久保存在应用程序存储或Application对象中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.