HydroHeiperGen
HydroHeiperGen

Reputation: 121

Is a Thread with an static WeakReference able to be garbage collected or does it force MemoryLeak?

I was asking myself, if this way:

public class thread_FrequentSendingThread extends Thread {

    private static WeakReference<thread_FrequentSendingThread> myThread;

public thread_FrequentSendingThread() {
    myThread = new WeakReference<>(this);
}

public static WeakReference<thread_FrequentSendingThread> getMyThread() {
    return myThread;
}
}

of using a static WeakReference will cause MemoryLeak. When is this Thread ready for being garbage collected?

What about Activites with a static WeakReference can they be garbage collected?

Is there a way to make these things ready for being garbage collected?

As this question is all about, when ever I use this WeakReference to get a Strong reference in a specified method or class, can they be garbage collected to?

Upvotes: 1

Views: 159

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93658

Lets assume the thread isn't running (if the thread is running, its a garbage collection root and cannot be freed). In that case it could be garbage collected. The rules for garbage collection is that it can be collected if there are no path of strong references to it from any GC root. A GC root is a thread, a static, a local variable (any local variable in any frame of any thread), or a JNI reference.

Whether its a good idea is another issue. FOr Activities its a horrible idea- there is no promise that you only have one instance of an activity at a time, so trying to use an static weak reference to the current activity (its usual use) will be broken and will cause problems when it refers to the wrong instance.

For a thread its less problematic, but still likely not the correct solution. Especially given that finished threads can't be restarted. I highly question if this is the best way to do what you're trying to accomplish.

Upvotes: 1

Related Questions