Do not place Android context classes in static fields. this is a memory leak. why?

Viewed 276

source code image

warning image

public static TestObject testObject;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    Log.d(TAG,"onCreate()");

    Context getApplicationContext = getApplicationContext();

    testObject = new TestObject(getApplicationContext);

The object of testObject is stored in the heap area and the reference variable in the static area stores the reference value of the testObject object. So if the object reference value is stored in the static reference variable and the reference value of the new object is stored, can an object with the reference value stored in the static reference variable be subject to GC because it no longer receives reference from the static reference variable? If it could be subject to GC, why would a warning message be generated that there is a possibility of a memory leak when using static?

1 Answers

If the life cycle of the application context is the same as when the app process starts and ends, even if the application context is entered as an argument to the object referenced in the static area, a memory leak will not occur. However, to use a structure that refers to an object in a static area, it is considered a better structure to use the singleton pattern. It is thought that computer resources can be saved by the new operator. Also, from a memory point of view, using a structure that refers to an object in a static area is considered bad because the referenced object is loaded into memory until the end of the process. In order to use less memory, I think that it is better to use the structure that refers to the object in the static area, and to use only the necessary objects.

Related