Reputation: 4256
We have, let's say, a very long thread:
private static class MyRunnable implements Runnable {
private final WeakReference<Context> contextRef;
private MyRunnable(Context leakable) {
contextRef = new WeakReference<>(leakable);
}
@Override public void run() {
Context context = contextRef.get();
if (context == null) return;
//VERY LONG TASK
//Would hard referencing context gotten from WeakReference.get() leak memory?
//Should contextRef be called each time context is needed?
}
}
private void startThread() {
new MyThread(this, new MyRunnable(this)).start();
}
The questions says all itself:
-Would hard referencing context gotten from WeakReference.get() leak memory?
-Should contextRef be called each time context is needed, in order to avoid leaking?
-The WeakReference.get() method calls a native method through JNI, would be get() method call expensive?
Upvotes: 1
Views: 391
Reputation: 533640
Would hard referencing context gotten from WeakReference.get() leak memory?
If an object is still being used, I wouldn't consider this a memory leak. If you are retaining memory you don't need, this can be a problem. You can clear/discard the string reference when you no longer need it.
Having a weak reference to an object doesn't change the behaviour of any strong reference.
Should contextRef be called each time context is needed, in order to avoid leaking?
Only if you are ok with it disappearing while you do this. If you need this to return the object (even before you call run()) you need to hold a string reference.
Note: your example, the first time you call get()
it can return null
but if it doesn't matter whether this runs at all, could you just not do it at all.
Upvotes: 1