I've got a background thread running in my application and I need to kill it safely. How can I kill a thread in java other than using a boolean flag? I have read that i cannot use thread.stop() anymore as it is not safe. but is there a proper way of doing this? can someone give me a code snippet for it please?
Thanks
Its never safe in any language to kill a thread- you don't know what that thread may be doing and what state it may leave behind. Using the cancel method with the thread occassionally checking isCanceled allows the thread to manage its own safety- it can choose to do this only when it would be safe to kill itself or to do the needed cleanup.
If you don't actually need to kill a thread but just want to wait until its over, use join.
If you absolutely need to kill a thread, go ahead and use stop. Just don't expect your state to be safe or consistent afterwards- this should really only be done when terminating the application/activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With