开发者

how to destroy thread in java after the completion of task

I开发者_运维知识库 am using a thread pool for my task. After completion of each task I am destroying the thread using Thread.stop() and Thread.destroy(). But after running my application (in Eclipse) for around 30 min. I am getting a Memory out of bound error.

Please suggest me how to kill the thread.


If you're using a thread pool, you shouldn't be terminating the thread to start with - the whole point of a thread pool is to reuse threads.

If you don't want to reuse the thread, then just start a new thread instead of using a thread pool - and just let the thread die, instead of calling stop or destroy. These methods are deprecated for good reason - they basically shouldn't be called.

It's not really clear how this would cause an out of memory exception though - is there any reason why you're focusing on threading as the probable cause?


To reinforce what @Jon Skeet said, it is a REALLY BAD IDEA to call the deprecated Thread.stop() or Thread.destroy() methods.

According to the javadoc, Thread.destroy() was fundamentally dangerous and was never implemented. The original idea was simply to kill the thread and break all of its monitor locks. If it happened to be in the middle of updating a shared data structure, the data structure would be left in an indeterminate state. Other threads waiting for the killed thread to notify some object would wait for ever.

Thread.stop() causes a ThreadDeath exception to be raised at an unexpected (to the code that was hit) place. It is a little bit more orderly than killing a thread, but unless all of the stopped thread (including anything that it calls) is carefully written with finally blocks to notify waiters, restore data structures, etc, you have the same problem.

Refer to Java Thread Primitive Deprecation for the whole story.


When the task is complete, the thread run should return. Do nothing more. That will take care of things.


In debug mode the threads are not cleared by the garbage collector. Try to run the app instead of run in debug mode and everything should be fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜