Why is my Java program leaking memory when I call run() on a Thread object?

后端 未结 3 466
情话喂你
情话喂你 2020-12-28 15:21

(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, b

3条回答
  •  情深已故
    2020-12-28 15:51

    This is a known bug in Java 1.4: http://bugs.sun.com/bugdatabase/view_bug.do;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 Thread is 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. A Thread object's run() method should not be called directly.

    A better way to code it is to implement the Runnable interface rather than subclass Thread. When you don't need a thread, call

    myRunnable.run();
    

    When you do need a thread:

    Thread myThread = new Thread(myRunnable);
    myThread.start();
    

提交回复
热议问题