(Jeopardy-style question, I wish the answer had been online when I had this issue)
Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.
But I found that my program would leak memory over time. What am I doing wrong?
This is a known bug in Java 1.4: https://bugs.java.com/bugdatabase/view_bug;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087
It’s fixed in Java 1.5 but Sun doesn’t intend to fix it in 1.4.
The issue is that, at construction time, a
Threadis added to a list of references in an internal thread table. It won’t get removed from that list until its start() method has completed. As long as that reference is there, it won’t get garbage collected.So, never create a thread unless you’re definitely going to call its
start()method. AThreadobject’srun()method should not be called directly.A better way to code it is to implement the
Runnableinterface rather than subclassThread. When you don’t need a thread, callWhen you do need a thread: