Java concurrent programming 9_ properly shut down threads

Source: Internet
Author: User
Tags volatile

Java does not provide any security mechanisms to terminate threads, although methods such as Thread.stop and suspend provide such mechanisms, but there are serious flaws that should be avoided using these methods.
It provides interrupts (interrupt), which is a collaborative mechanism that enables one thread to terminate the current work of another thread.
A collaboration mechanism is to set up a "requested cancellation (cancellation requested)" Flag, and the task periodically views the flag.

canceled requested Flag
privatevolatileboolean cancelled;publicvoidrun() {      while (!cancelled) {        doSomething();    }}publicvoidcancel() {    true;}

This is done by polling the flag to determine whether to continue the task. If the flag cancel is not invoked, the task will continue to run. Volatile ensures the visibility of the logo, making the process work reliably.
The cancel mechanism of cancel causes the task to exit, but it takes a certain amount of time to exit the process. In extreme cases when a task calls a blocking method, such as sleep/wait/... Then the task may never check the cancellation flag, so it never ends.

 Public  class closethread extends Thread {      Private volatile BooleanCancelled Public void Run() { while(!cancelled)        {dosomething (); }    }Private void dosomething() {Try{Thread.Sleep (10000); }Catch(Interruptedexception e)        {E.printstacktrace (); }    } Public void Cancel() {cancelled =true; } Public Static void Main(string[] args) {FinalClosethread Closethread =NewClosethread ();        Closethread.start (); Timer timer =NewTimer (); Timer.schedule (NewTimerTask () {@Override             Public void Run() {closethread.cancel (); System.out.println ("Closethread isAlive--"+ closethread.isalive ()); }        }, -); }}

Print as follows:

Closethread Isalive–true

Polls the status flag inside the Run method, resumes the task when cancelled is false, and calls the Cancel method after 2S to set the cancelled flag to true.
You can see that when it takes longer in the Run method, it can be polled every 10S, that is, it takes a certain amount of time to exit the task, and the call cannot close the thread and the thread can close after 10S. In the extreme case, the thread never shuts down when a blocking method is encountered.
So there is a problem with the way the flags are set, and the custom cancellation mechanism does not interact well with the blocking methods.

using interrupts to close a thread

Typically, interrupts are the most logical way to implement cancellation.

Interrupts are a collaborative mechanism by which a thread can notify another thread, telling him to stop the current work in a suitable or probable situation, and to perform other tasks instead.

public  class  thread  { public  void  interrupt  () {   ... }    //interrupts a thread  public  boolean  isinterrupted   () { ... }    //gets the interrupt flag to determine whether to break the  public  static  boolean  interrupted   () { ... } //clears the interrupt state and returns the status value before it }  

Each thread has a Boolean type of interrupt state. The interrupt state of this thread will be set to true when it is disconnected.
Calling interrupt does not immediately stop the work being done by the target thread, but simply passes the message of the request interruption, in other words, modifies only the thread's flag field.
The correct understanding of the interrupt operation is that he does not actually interrupt a running thread, but simply makes an interrupt request and then interrupts itself by the thread at the next appropriate moment (the cancellation point). such as Sleep/wait/join will strictly deal with such requests. An exception is thrown when they receive an interrupt request or when they find an interrupt state that has been set up at the start of execution.

To use interrupts to cancel a thread task in three different situations

-Interrupt occurs in a non-blocking state
-interruptible blocking in blocked state
-Non-disruptive blocking in blocked state

interrupt occurs in a non-blocking state

When a thread is interrupted in a non-blocking state, its interrupt state is set, and if interruptedexception is not triggered, the interrupt state is maintained and the interrupt status is determined based on the check interrupt state.
You can choose the appropriate polling frequency by polling the current thread's interrupt state in the task code, and you need to weigh between efficiency and responsiveness.

interruptible blocking in blocked state Blocking library function interrupts

When the methods of blocking libraries such as Wait/sleep/blockingqueue.put are returned early in the discovery of interrupts, the actions they perform at the time of interruption include clearing the interrupt state and throwing interruptexception.

publicvoidrun() {      while (!Thread.currentThread().isInterrupted()) {        doSomething();    }}  privatevoiddoSomething() {    try {        Thread.sleep(1001000);        // 阻塞操作    catch (InterruptedException e) {        // ?????// 要有对应的中断响应    }}publicvoidcancel() {    interrupt();}

Explicit detection in the while is more responsive to interrupts.

How do I respond to interrupts?

How to respond to interrupts
1. Pass the exception, making the calling method also an interruptible blocking method. Simply put, add a declaration that throws an exception.
2. Resume the interrupt state so that the upper code of the call stack can handle it. The standard practice is to call interrupt again in the catch to restore the interrupt state, allowing the upper-level code to handle it.
In the example above, you can call interrupt again in the catch to resume the interrupt state and exit when the condition is not met again while the while loop, consider the following example
When Interruptexception is captured, interrupts can be masked unless an interrupt policy is implemented in the code. What does an interrupt policy mean when you receive an interrupt request? For example, the following interrupt policy is the thread will exit immediately, no upper code needs to know the interrupt information.

// InterruptException中屏蔽中断,是因为他已经知道线程将要结束了publicvoidrun() {      try {        while (!Thread.currentThread().isInterrupted()) {                Thread.sleep(101000);        }    catch (InterruptedException e) {        /* 允许线程退出  */    }}  publicvoidcancel() {    interrupt();}
cases where the interruptible blocking method is not supported but can still be called

The

does not support operations that cancel but can still invoke the interruptible blocking method. When catch-to-break should save the interrupt state locally and resume the interrupt state before returning, instead of recovering when the interrupt state is captured, premature setting of the interrupt state may cause an infinite loop, since most interruptible blocking methods check the interrupt state at the entrance, And immediately throws interruptexception

when the state is found to be set.

publicgetNextTask(BlockingQueue<Task> queue) {      booleanfalse;      try {          while (true) {              try {                  return queue.take();              catch (InterruptedException e) {                  true;              }          }      finally {          if (interrupted)              Thread.currentThread().interrupt();      }  }
non-disruptive blocking in blocked state

Many blocking methods respond to interrupt requests by early return or by throwing interruptexception, which makes it easy for developers to build a task that can cancel a request, but not all of the blocking methods or blocking mechanisms can respond to interrupts. For example, socket I/O, waiting for a built-in lock, interrupt request can only set the interrupt state of the thread, there is no other effect. We can use a similar interrupt to stop these threads, but this requires knowing the cause of the thread blocking.
Synchronous socket I/O Although both the read and write methods in InputStream and OutputStream do not want to break, by closing the underlying socket, Can cause a socketexception to be thrown by a thread that is blocked by executing methods such as read and write. That is, when you need to cancel the task to close the underlying socket, in the socketexception can respond to interrupts.

 Public  class closesocket extends Thread {      PrivateSocket socket;PrivateInputStream in; Public  closesocket(Socket socket)throwsIOException { This. socket = socket; This. in = Socket.getinputstream (); }@Override     Public void Interrupt() {Try{//Closing This socket would also close the socket ' s InputStream and OutputStream.Socket.close (); }Catch(IOException e) {        }finally{Super. interrupt (); }    }@Override     Public void Run() {Try{byte[] buf =New byte[1024x768]; while(true) {intnum = In.read (BUF);// ......}        }Catch(IOException e) {//thread quits directly.}    }}

The interrupt method has been rewritten so that its skill-handling standard interrupts can also close the underlying socket, so that it can be interrupted and stop the current work regardless of whether the thread is blocked in the Read method or blocked in an interruptible blocking method.

Java Thread Primitive is not recommended for Thread.stop and suspend deprecation

Java concurrent programming 9_ properly shut down threads

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.