`
zhubin215130
  • 浏览: 142313 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[转]解析为什么Thread中的stop(), suspend(), resume() 会被Deprecated

    博客分类:
  • JAVA
阅读更多

Why is Thread.stop deprecated?

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) 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. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.



Couldn't I just catch the ThreadDeath exception and fix the damaged object?

In theory, perhaps, but it would vastly complicate the task of writing correct multithreaded code. The task would be nearly insurmountable for two reasons:

  1. A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
  2. A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
In sum, it just isn't practical.



What about Thread.stop(Throwable)?

In addition to all of the problems noted above, this method may be used to generate exceptions that its target thread is unprepared to handle (including checked exceptions that the thread could not possibly throw, were it not for this method). For example, the following method is behaviorally identical to Java's throw operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:

    static void sneakyThrow(Throwable t) {
        Thread.currentThread().stop(t);
    }



What should I use instead of Thread.stop?

Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. (This is the approach that JavaSoft's Tutorial has always recommended.) To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).

For example, suppose your applet contains the following startstop and run methods:

    private Thread blinker;

    public void start() {
        blinker = new Thread(this);
        blinker.start();
    }

    public void stop() {
        blinker.stop();  // UNSAFE!
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
You can avoid the use of Thread.stop by replacing the applet's stop and run methods with:
    private volatile Thread blinker;

    public void stop() {
        blinker = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }



How do I stop a thread that waits for long periods (e.g., for input)?

That's what the Thread.interrupt method is for. The same "state based" signaling mechanism shown above can be used, but the state change (blinker = null, in the previous example) can be followed by a call to Thread.interrupt, to interrupt the wait:

    public void stop() {
        Thread moribund = waiter;
        waiter = null;
        moribund.interrupt();
    }
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
    Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException as soon as it is able.



What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. 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. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.



Why are Thread.suspend and Thread.resume deprecated?

Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.



What should I use instead of Thread.suspend and Thread.resume?

As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.

For example, suppose your applet contains the following mousePressed event handler, which toggles the state of a thread called blinker:

    private boolean threadSuspended;

    Public void mousePressed(MouseEvent e) {
        e.consume();

        if (threadSuspended)
            blinker.resume();
        else
            blinker.suspend();  // DEADLOCK-PRONE!

        threadSuspended = !threadSuspended;
    }
You can avoid the use of Thread.suspend and Thread.resume by replacing the event handler above with:
    public synchronized void mousePressed(MouseEvent e) {
        e.consume();

        threadSuspended = !threadSuspended;

        if (!threadSuspended)
            notify();
    }
and adding the following code to the "run loop":
                synchronized(this) {
                    while (threadSuspended)
                        wait();
                }
The wait method throws the InterruptedException, so it must be inside a try ... catch clause. It's fine to put it in the same clause as the sleep. The check should follow (rather than precede) the sleep so the window is immediately repainted when the the thread is "resumed." The resulting run method follows:
    public void run() {
        while (true) {
            try {
                Thread.currentThread().sleep(interval);

                synchronized(this) {
                    while (threadSuspended)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
Note that the notify in the mousePressed method and the wait in the run method are inside synchronized blocks. This is required by the language, and ensures that wait and notify are properly serialized. In practical terms, this eliminates race conditions that could cause the "suspended" thread to miss a notify and remain suspended indefinitely.

While the cost of synchronization in Java is decreasing as the platform matures, it will never be free. A simple trick can be used to remove the synchronization that we've added to each iteration of the "run loop." The synchronized block that was added is replaced by a slightly more complex piece of code that enters a synchronized block only if the thread has actually been suspended:

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }

In the absence of explicit synchronization, threadSuspended must be made volatile to ensure prompt communication of the suspend-request.

The resulting run method is:
    private boolean volatile threadSuspended;

    public void run() {
        while (true) {
            try {
                Thread.currentThread().sleep(interval);

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }



Can I combine the two techniques to produce a thread that may be safely "stopped" or "suspended"?

Yes; it's reasonably straightforward. The one subtlety is that the target thread may already be suspended at the time that another thread tries to stop it. If the stop method merely sets the state variable (blinker) to null, the target thread will remain suspended (waiting on the monitor), rather than exiting gracefully as it should. If the applet is restarted, multiple threads could end up waiting on the monitor at the same time, resulting in erratic behavior.

To rectify this situation, the stop method must ensure that the target thread resumes immediately if it is suspended. Once the target thread resumes, it must recognize immediately that it has been stopped, and exit gracefully. Here's how the resulting run and stop methods look:

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);

                synchronized(this) {
                    while (threadSuspended && blinker==thisThread)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

    public synchronized void stop() {
        blinker = null;
        notify();
    }
If the stop method calls Thread.interrupt, as described above, it needn't call notify as well, but it still must be synchronized. This ensures that the target thread won't miss an interrupt due to a race condition.



What about Thread.destroy?

Thread.destroy has never been implemented. If it were implemented, it would be deadlock-prone in the manner of Thread.suspend. (In fact, it is roughly equivalent to Thread.suspend without the possibility of a subsequent Thread.resume.) We are not implementing it at this time, but neither are we deprecating it (forestalling its implementation in future). While it would certainly be deadlock prone, it has been argued that there may be circumstances where a program is willing to risk a deadlock rather than exit outright.




Why is Runtime.runFinalizersOnExit deprecated?

Because it is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. While this problem could be prevented if the class whose objects are being finalized were coded to "defend against" this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.

Further, the call is not "thread-safe" in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!

 

分享到:
评论

相关推荐

    线程外部挂起恢复控制(不使用Suspend与Resume中止线程)

    自.NET 2.0以来,Thread.Suspend()与Thread.Resume()方法已过时,VS提示可以使用如Monitor等技术,但是对于刚接触同步控制的人来说理解起来太复杂。本人利用Thread.Abort()与Thread.Interrupt()可以引起目标线程异常...

    Andriod PM suspend-resume 电源管理

    在设备初始化时,例如`mxc_board_init`,会将设备注册到电源管理列表`dpm_list`,在后续的`dpm_suspend`和`dpm_resume`过程中,系统会遍历此列表执行相应的操作。 此外,Android内核提供了接口函数,如`wake_lock_...

    resume_suspend.txt

    - 当设备进入 Suspend 状态时,LCD 可能会被关闭以节约电力。 - 在 Resume 时,LCD 需要重新初始化并恢复到之前的状态。 #### TP (Touch Panel) - **定义**:触摸屏面板,用户与设备交互的主要接口。 - **控制**...

    hal库 FreeRTOS-Task-suspend&resume

    hal库 FreeRTOS-Task-suspend&resume

    不能调用Suspend/TerminateThread的原因

    在这个例子中,main线程不断地suspend和resume子线程,而子线程不断地执行printf语句。由于printf函数内部使用了Critical Section,而子线程在执行printf时可能会hold这个Critical Section。如果main线程在这个时候...

    【脚本】Registering an AFTER SUSPEND Trigger

    当定义了一个AFTER SUSPEND触发器,它会在一个事务被挂起后执行,这可能用于记录事务状态、更新审计日志或者执行其他与事务管理相关的操作。 描述中提到的博文链接虽然没有提供具体内容,但我们可以推断这篇博文...

    线程组ThreadGroup

    ThreadGroup 还提供了一些其他的方法,例如 stop() 方法可以停止当前 ThreadGroup 中的所有线程,resume() 方法可以恢复当前 ThreadGroup 中的所有线程,suspend() 方法可以暂停当前 ThreadGroup 中的所有线程等。...

    RT-Thread常见函数.zip_RTT_rt thread_rt-thread函数_rt_thread函数_手册

    1. **任务管理**:RTT的任务(Task)是系统执行的基本单元,开发者可以通过`rt_thread_create`创建任务,`rt_thread_startup`启动任务,`rt_thread_delete`删除任务,以及`rt_thread_suspend`和`rt_thread_resume`...

    ACER_SUSPEND & REBOOT V1.1.RAR

    描述中的内容与标题相同,进一步确认了这是一个名为"ACER_SUSPEND & REBOOT V1.1"的软件版本,版本号为1.1,可能包含了一些改进和修复了上一版本的问题。 标签"ACER_SUSPEND&R"简化了标题中的关键词,强调了该软件...

    Android-suspend-and-resume.rar_android_android 唤醒_linux suspend

    休眠/唤醒在嵌入式Linux中是非常重要的部分,嵌入式设备尽可能的进入休眠状 态来延长电池的续航时间.这篇文章就详细介绍一下Linux中休眠/唤醒是如何工作 的, 还有Android中如何把这部分和Linux的机制联系起来的.

    LINUXSuspend流程[文].pdf

    - 该函数位于`kernel/power/earlysuspend.c`中,用于调度早期挂起(`early_suspend`)和晚期恢复(`late_resume`)的工作。 - **代码示例**: ```c request_suspend_state() { queue_work(suspend_work_queue, &...

    ThreadX内核用户手册,含SMP多核(中文版).pdf

    * tx_thread_resume():恢复线程的执行 * tx_thread_sleep():使线程进入睡眠状态 * tx_thread_suspend():暂停线程的执行 * tx_thread_terminate():终止线程的执行 * tx_thread_wait_abort():等待线程的终止 ...

    rt-thread 完整源代码

    RT-Thread 是一款主要由中国开源社区主导开发的开源实时操作系统。实时线程操作系统不仅仅是一个单一的实时操作系统内核,它也是一个完整的应用系统,包含了实时、嵌入式系统相关的各个组件:TCP/IP协议栈,文件系统...

    线程的挂起、唤醒和终止

    在Java中,可以使用`Thread.suspend()`方法来挂起线程,但需要注意,这个方法会使得线程陷入阻塞状态,直到被其他线程唤醒。然而,`Thread.suspend()`和相应的`Thread.resume()`方法已不推荐使用,因为它们可能导致...

    Java多线程-Thread类的常用结构及线程优先级

    - `suspend()` 和 `resume()`:挂起和恢复线程,由于可能导致死锁,这两个方法也被废弃。 二、线程的优先级 1. 线程调度策略 Java中的线程调度有两种策略:抢占式调度和合作式调度。Java采用抢占式调度,优先级...

    NXP i.MX RT1052 RT-Thread实战:线程管理

    在RT-Thread中,线程可以理解为任务或子程序,它们并发执行,共享进程的内存空间。线程管理主要包括线程创建、销毁、挂起、恢复、优先级设置等操作。 #### 1. 线程创建 在RT-Thread中,开发者可以通过`rt_thread_...

    i915_suspend.rar_V2

    标题 "i915_suspend.rar_V2" 暗示了这是一个关于英特尔i915图形控制器在Linux系统中挂起(suspend)功能的更新版本,可能是针对内核2.13.6的一个补丁或驱动程序。在这个压缩包里包含的文件 "i915_suspend.c" 是C语言...

    Java多线程与并发系列22道高频面试题(附思维导图和答案解析)

    使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期废弃的方法;使用interrupt方法中断线程。 三、notify和notifyAll的区别 notify和notifyAll都是用于线程间的通信的方法,但是...

    理解多线程,写一个多线程应用程序,要求能在用户级实现线程的调度,如启动、挂起、恢复、停止,的C thread、java thread实现。

    // thread.resume(); // 恢复线程(与suspend配合使用) // thread.stop(); // 停止线程(不推荐,因为不安全) // thread.interrupt(); // 中断线程,通常用于通知线程退出循环 } } ``` 在用户级线程调度中,...

Global site tag (gtag.js) - Google Analytics