Reputation: 140
i am not facing memory leak problem but i need to know how memory leak occurs. form here the below code gives memory leak.
private static Drawable sBackground;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
if (sBackground == null) {
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground);
setContentView(label);
}
can someone give me a full explanation of how the memory leak occurs ? and how the gc cannot collect the references ?.
and also plz explain whether the below code leak memory ? , if it is how it happens?
private static Context context;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(context);
label.setText("Leaks are bad");
setContentView(label);
}
Upvotes: 0
Views: 2436
Reputation:
how GC
will run if you have the reference
of the object. You have to release the object first.
An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static references in other words you can say that an object becomes eligible for garbage collection if its all references are null.
Please read more here How Garbage Collection works in Java
Also read this it will clarify your doubts about GarbageCollector
Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
But in case of static reference
you still have the reference of that object so the GC
wont run on that object.
Read more here What is Automatic Garbage Collection?
Upvotes: 3