0

I know that it is deprecated to use Thread.stop() and I allready know the alternative ways to stop a thread. But what are the direct consequences of Thread.stop() and what makes Thread.stop() so "dangerous"?.

If I call Thread.stop() in the end of an activity (onDestroy) will it cause any problems ( I want to prevent the Thread from accessing objects in my activity immediately)?

thx & regards

user2224350
  • 2,262
  • 5
  • 28
  • 54
  • 3
    If you have not read it yet, have a look at http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html – PM 77-1 Sep 11 '13 at 16:40
  • @PM77-1 from that link (good link by the way): It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either – rolfl Sep 11 '13 at 16:46
  • 1
    Android's `stop()` implementation is [`throw new UnsupportedOperationException()`](https://android.googlesource.com/platform/libcore/+/android-4.3_r2.2/luni/src/main/java/java/lang/Thread.java). This won't stop the thread or affect it in any way. – zapl Sep 11 '13 at 17:19

2 Answers2

1

The documentation indicates that Thread.stop() throws a ThreadDeath exception, and that any finally blocks, and any code that intercepts/catches ThreadDeath will still run. If your objective is to prevent the thread from accessing objects, then this is not the solution.

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • Will JVM kill the Thread if it runs as daemon, when the activity gets finished ? – user2224350 Sep 11 '13 at 17:37
  • I'm not sure. In pthreads, which I believe is the underlying implementation of Android threads, a program will wait for all threads to finish before exiting the process. So I would guess that you need to manually terminate the other threads. But I'm not totally sure. – BinderNews Sep 11 '13 at 17:43
  • @user2224350 No because Activity finish does not stop the Application process. Threads will keep running until the Application process is explicitly killed by the system. And that happens rarely since apps are intended to stay alive in background for as long as possible to reduce re-start times. Deamon threads are therefore essentially useless in Android. – zapl Sep 11 '13 at 17:50
  • So I have to check within each thread before each "unsafe-call" if the thread is legitimized to run ? That seems to be not very elegant.. – user2224350 Sep 11 '13 at 18:54
1

Thread.stop() is dangerous because it releases all locked objects. What this means is that if the object is, for example, updating an array and it has locked it so other threads are waiting for this thread to finish before using the array, and you call Thread.stop(), then the array will only be partially updated. This can lead to hard-to-debug errors in other parts of the code.

BinderNews
  • 570
  • 3
  • 10