Java multi-thread cancellation and shutdown

Source: Internet
Author: User
Tags exit in

It's not easy to stop a thread safely, quickly, and reliably. Java does not provide any mechanism to safely terminate the thread. But Java provides interrupts (interrupt) so that one thread can terminate the current work of another thread

Each thread has a Boolean type of interrupt state. The interrupt state of this thread will be set to not true when disconnected. Thread contains methods for interrupting threads and for checking thread interrupts.

The interrupt () method can interrupt the target thread.

The Boolean Isinterrupt () method can return the status of whether the target thread is interrupted.

The static Boolean interrupted () will return and clear the current interrupt state of the thread, which is the only way to clear the thread interrupt state.

Calling the interrupt () method does not mean that the target thread is immediately stopped from working, but only the message that the request was interrupted is passed. Then the thread interrupts itself at the next appropriate time.

  Interrupt Policy

Each thread should contain its own endpoint policy in response to the interrupt state. The interrupt policy specifies how threads respond to interrupt requests-----What should be done when an interrupt request is found, which units of work are atomic for interrupts, and interrupts at multiple speeds.

response Interruption

  A . There are two usage policies that can be used to handle interruption exceptions when calling interruptible blocking functions

1. Pass the exception so that your method becomes an interruptible blocking method.

Passing an exception requires just adding throws interruptedexception outside the method,

2. Resume the interrupt state so that the upper code in the call stack can handle it.

You can call the interrupt () method to resume the interrupt state.

Two. If the code does not invoke an interruptible blocking method, it can still be interrupted by polling the interrupt state in the current thread.

  Cancel with future implementation

  Calling the Executorservice.submit method returns a future object.

Future.cancel (Boolean B). can be used to cancel the current task. If B is set to true, it means that if the thread is running then it is interrupted and if it is set to false, it will not run if it is not running, which means that if it is running, it will not be executed without interruption and not running. The return value simply indicates whether the interrupt state was set successfully, rather than the thread has been interrupted.

  Handling non-disruptive blocking

  java.io the sync Socket,io in the package to directly close the underlying socket socket.

java.io to close the link

Selector Asynchronous IO can call the close or Wakeup method to return early.

  To turn off thread-based services

Applications typically create services that have multiple threads. The life cycle of these services is usually longer than the way they were created, and if the application is ready to exit, the service-owned thread also needs to end, so the service should provide a life-cycle approach to close itself and the threads it owns.

Executorservice provides the shutdown and Shutdownnow two ways to stop the service. The Shutdownnow method stops accepting the new task first, then closes the task that is being executed, and finally returns a task that has not yet been submitted. The Shutdown method stops accepting the new task first, and then waits for all the committed tasks in the queue to complete, and the last execution is closed. The Shutdownnow has better responsiveness but less security.

Another way to turn off producers---consumer services is to use poison pill objects. Poison pills can only be used if the number of producers and consumers is known. And only in the unbounded queue poison pill object can work normally. And when the number of producers and consumers is large, this approach will become difficult to use.

  Handling an unhealthy thread termination

1. Take the initiative to deal with it. In the life cycle of a task processing thread, many unknown code is invoked through an abstraction mechanism, and we should be skeptical of the correct behavior of the code executed in these threads, so these threads should be executed in the Try-catch code block, so that the unchecked exceptions can be captured. Or you can make sure that the framework is able to know the try-finally of the thread exit in the code block and make the correct corresponding.

2. Uncaughtexceptionhandler treatment provided by THREADAPI. Uncaughtexceptionhandler can detect the termination of a thread due to an unhandled exception. Only the task submitted by the Execute method can pass an exception to the unhandled exception handler, and the method submitted by submit, whether thrown or unchecked, will be considered part of the return status of the task. If a task submitted by submit throws an exception, the exception will be re-thrown in the execueexcetion by the Future.get package.

These two methods complement each other and effectively prevent thread leaks by combining the two methods efficiently.

Java multi-thread cancellation and shutdown

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.