The seventh chapter: cancel and close--java concurrent programming combat

Source: Internet
Author: User
Tags volatile

Java does not provide any mechanism to safely terminate a thread (although the Thread.stop and suspend methods provide such a mechanism, but because of a flaw, you should avoid using

Interrupt: A collaboration mechanism that enables one thread to terminate the current work of another thread

stopping immediately causes the shared data structure to be in an inconsistent state , and when it needs to be stopped, an interrupt request is made, and the thread that is asked to interrupt finishes his current task and determines whether to stop

I. CANCELLATION of MISSION

If the external code can be placed in the "done" state before an operation is completed, the operation can be canceled . (User request cancellation, time-limited actions < concurrency lookup results, one thread found can cancel other threads >, application events, errors, shutdown)

Cancellation Policy: Define the "how" and "when" and "what" of the cancel operation in detail, that is, how the other code requests that the task be canceled, when the task checks if cancellation has been requested, and what action should be taken in response to the cancellation request

Example: setting the volatile variable to a cancellation flag, checking before each execution

1 Private volatile Booleancanceled;2     3 @Override4      Public voidrun () {5BigInteger p =Biginteger.one;6          while(!canceled) {7p =p.nextprobableprime ();8             synchronized( This) {//adding prime numbers synchronously9 Primes.add (p);Ten             } One         } A}

Note: This is a problematic cancellation method, and if the thread blocks after the add operation, it will not run to the code that verifies the blocking state even if the cancellation state is set, so it will block forever

1. Interruption

  This mechanism can be used by a thread to notify another thread, telling it to stop the current work as appropriate or possible, and to perform other tasks instead. (It is not appropriate to use interrupts outside of cancellation)

Calling interrupt does not mean that the target thread is immediately stopped from working, but only the message that the request was interrupted is passed. Will interrupt itself at the next cancellation point, such as wait, sleep,join, etc.

1  Public classThread {2       Public voidInterrupt () {...}//interrupt target thread, resume interrupt State3       Public BooleanIsinterrupted () {...}//returns the interrupt status of the target thread4       Public Static BooleanInterrupted () {...}//clears the interrupt state of the current thread and returns the value before it (for which the interrupt state has been set but has not yet been interrupted)5      ...6}

Blocking library methods, such as Thread.Sleep and object.wait, will check when a thread is interrupted and return early when it is discovered. The actions they perform in response to an outage include clearing the interrupt state, throwing a interruptedexception, indicating that the blocking operation ended prematurely due to an outage .

    • The detected interrupt is displayed! Thread.CurrentThread (). isinterrupted () after launch
    • Blocking method Interruptedexception after catching the exit

2. Interrupt policy--Specify how the thread interprets an interrupt request--what should be done when an interrupt request is found

Because each thread has its own interrupt policy, this thread should not be interrupted unless you know what the interrupt means for that thread.

3. Response Interruption

    • Passing exception (throws Interruptedexception)

    • Restores the interrupt state so that the upper code of the call stack can handle it. (Thread.CurrentThread (). interrupt ();)

4, through the future to achieve cancellation

Boolean Cancel (Boolean mayinterruptifrunning);

    • If the task has completed, or has been canceled, or cannot be canceled for some other reason, the attempt will fail and return false
    • When you call Cancel, if the call succeeds and the task has not been started, the task will never run
    • If the task is already executed, the mayinterruptifrunning parameter determines whether the interrupt operation is issued to the thread performing the task

5, handling non-disruptive blocking --for some blocking operations, just set the interrupt state

    • Java.io the synchronous socket I/O in the package. Although both read and write methods in InputStream and OutputStream do not respond to interrupts, the underlying socket can be turned off to cause a socketexception to be thrown by a thread that is blocked by executing a read or write method.
    • java.io the synchronous I/O in the package. When you break a thread that is waiting on a interruptiblechannel, Will throw Closedbyinterruptedexception) and close the link (this will also cause other threads that are blocked on this link to also throw closedbyinterruptexception). When a interruptiblechannel is closed, all threads that are blocked on the link operation are thrown asynchronouscloseexception. Most of the standard channel implementations are interruptiblechannel.
    • The selector asynchronous I/O. If a thread blocks while calling the Selector.select method (in Java.nio.channels), calling the close or wakeup method causes the thread to throw closedselectorexception and return early.
    • Gets a lock. If a thread is blocked because it waits for a built-in lock, the interrupt cannot be responded to because the thread thinks it is definitely getting a lock, so the interrupt request will not be heeded. However, the Lockinterruptibly method is provided in the lock class, which allows you to still respond to interrupts while waiting for a lock.
1 //overwrite the interrupt method to make an interrupt request2 @Override3      Public voidinterrupt () {4         Try {5Socket.close ();//close the socket before interrupting6}Catch(IOException e) {7             8}finally{9             Super. Interrupt ();Ten         } One}

6, the use of newtaskfor to encapsulate non-standard cancellation

The seventh chapter: cancel and close--java concurrent programming combat

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.