How to kill thread in java after task is completed

I use thread pool for my task. After completing each task, I destroy the thread using Thread.stop() and Thread.destroy() . But after starting my application (in Eclipse) about 30 minutes. I get a memory error from a related error.

Please suggest me how to kill the stream.

+6
java multithreading
source share
4 answers

If you use a thread pool, you should not interrupt a thread to start with it - the whole point of the thread pool is to reuse the threads.

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

It is not entirely clear how this could cause an exception from memory - is there a reason why you are focusing on the thread as a probable reason?

+13
source share

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

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

Thread.stop() throws a ThreadDeath exception at an unexpected (to the affected code) location. This is a bit more streamlined than killing a stream, but if all the stopped threads (including everything that it causes) are carefully written by finally blocks to notify waiters, restore data structures, etc., you have the same problem.

See Java Primary Deprecation for the whole story.

+5
source share

When the task is completed, the thread flow should return. Do nothing else. This will take care of things.

+4
source share

In debug mode, threads are not cleared by the garbage collector. Try starting the application instead of starting in debug mode, and everything should be fine.

0
source share

All Articles