Maintaining a memory leak test?

If I have a code like this:

public class MyActivity extends Activity { private SingletonClass singletonInstance; ... @Override protected void onCreate(Bundle savedInstanceState) { singletonInstance = SingletonClass.getInstance(); } ... } 

My understanding is that Activity will stay alive because it refers to a static instance and therefore will not be GC'd. However, this does not cause me any problems in my application. Don't I understand GC or is it really a memory leak and should I avoid referencing my singleton class?

+4
source share
2 answers

I have studied your doubts, and I confirm my answer:

This will happen if you declare singletonInstance static. For your business, singletonInstance is just an instance of SingletonClass. Remember that there is no such thing as a โ€œstatic instanceโ€, an instance is just an object of this class, which makes it static, the way you declare it in your scope. For MyActivity, singletonInstance is not static, even if inside SingletonClass you are referring to the same object / instance, and there it is declared as static.

Thus, your activity can be cleared by the GC without any problems. I have a similar implementation on Android, and it includes a Service, it worked for hundreds of hours without any memory or performance issues ...

Hello

+1
source

I use Square's LeakCanary to detect memory leaks in an Android app, and one of my actions detected a leak due to a link stored in a static single object.

My Activity is the same structure as in Q, where the Activity has a reference to the Presenter singleton class, but the link is not static.

 public MyActivity extends Activity { private MyPresenter mPresenter; ... onCreate() { mPresenter = MyPresenter.getInstance() ... } } .. public class MyPresenter { // Different class private static MyPresenter mInstance; ... singleton code ... } 

I read this link and I assume that makes sense. http://www.javaworld.com/article/2071737/core-java/plug-memory-leaks-in-enterprise-java-applications.html

When an instance of the Singleton class is created, it remains in memory for the lifetime of the application. Other objects will also have a live link to it and, as a result, will never collect garbage.

Recommendation: - Avoid references to long-acting objects. If such use cannot be avoided, use a weak link, a type of object reference that does not interfere with garbage collection.

+1
source

Source: https://habr.com/ru/post/1482575/


All Articles