简体   繁体   中英

How Java thread.stop() work?

I am actually looking for an easier way to kill the thread not matter where the thread is running at. But most of the solutions in internet point me to use boolean flag to control the execution of the thread, if I want to stop the thread then set the boolean variable to false.

But what if the task that in the runnable is a LONG linear task, which mean the task is not repeating? In that case, it is not so easy to create a 'while' loop to cover the whole block of task.

It is really so temptative to use Thread.stop but the warning "Deprecated" seem like quite dangerous to use. I have read through this article Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?

but I can't understand

If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged.

What does the "inconsistent state" mean? I appreciate if anyone can explain about this.

I want to extend my question to a more lower level of view, let say i = i + 1; in JVM (perhaps assembly language alike), maybe this Java statement will be split into few smaller instructions, for example like move i ; add i ; get i into memory 0x0101 move i ; add i ; get i into memory 0x0101 move i ; add i ; get i into memory 0x0101 (This is an example! I totally don't know assembly language!)

Now, if we call thread.stop, where actually will it stop at? Will the thread stop after a COMPLETED Java statement, or could be in the middle of the "assemble language"? If the answer is the second, could it be reason that we said

Such objects are said to be damaged.

?

Ok, my question is kind of confused, hope someone can understand and explain. Thanks in advance.

"Damaged object" is a high-level concept, it doesn't happen at the JVM level. A programmer designs his class with thread safety in mind by guarding critical sections with locks. It is an invariant of his class that each critical section either runs in full, or doesn't run at all. When you stop a thread, a critical section may have been interrupted in the middle, so disrupting the invariant. At that moment the object is damaged .

Stopping a thread conceals many more dangers, like no cleanup performed, no acquired resources released, etc. If a thread doesn't give up what it is doing, there is no way to make it stop without compromising the entire application.

In practice, whenever one faces the need to run alien code that may need to be forcefully aborted, this must be done in a separate process because killing a process at least performs OS-level cleanup and does a much better job of containing the damage.

The "inconsistent state" means state of data as your application cares about, state that your application logic have carefully produced by making your application thread-safe with locks/monitors etc.

Imagine you have this simple method:

public synchronized void doSomething() 
{
      count++;
      average = count/total;
}

This method, along with other methods are synchronized, as multiple threads are using this object. Perhaps there's a

public synchronized AverageAndCount getMeasurement() 
{
   return new AverageAndCount(average, count);
}

This assures that a thread can't read an incomplete measurement, ie if the current measurement is in the process of being calculated inside eg doSomething(), getMeasurement() will block/wait until that's finished.

Now, imagine the doSomething is run in a thread, and you call .stop() on that thread.

So the thread might be stopped right after it performs count++; , the monitor that's held is unlocked and the method terminates and average = count/total; is not executed,

That means the data is now inconsistent. Anyone calling getMeasurement() afterwards will now get inconsistent data.

Note also that at this point it is not very relevant whether this happens at a java statement level, or at a lower level, the data can be in an inconsistent state that you can't reason about in any case.

I'm no expert but this is what I think. If you use Thread.stop() you cause the ThreadDeath exception that will cause all monitors to be released. Since you provoke an exception you are applying an unnatural behaviour to the state of things.

Other threads relying on those monitors could enter in an inconsistent situation because they were not expecting it. And I don't think you can even anticipate the monitors releasing order.

I believe the concern is that the thread may be in the middle of a synchronize block performing multi-step updates to an object's members. If the thread is stopped abruptly, then some updates will have occurred but not others and now the object's state may render it unusable.

I have my doubts that the ThreadDeath handling will release a Lock backed by the AbstractQueuedSynchronizer which could leave the application on the path to a sort of deadlock.

At any logical point in your long sequence of code you can simply add:

if (Thread.interrupted())  {
    throw new InterruptedException();
}

...this will exit execution at this point if it is determined that Thread.interupt() was called on the Thread executing the long running task.

停止线程的方法并不清楚。每当run()方法完成或发生任何异常然后线程停止时,实际上都不推荐使用stop()方法。使用boolean flag变量.Bydefault“false”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM