"Java Concurrent Programming Practical" reading notes 6--Cancel and close

Source: Internet
Author: User

The main content of this chapter is about how to make tasks and threads safe, fast and reliable to stop.

7.1 Task Cancellation

There is no secure preemption in Java to stop threads, but you can use some collaboration mechanisms, such as:

Allow the prime number generator to cancel after 1 seconds (and not stop just after 1 seconds of running, because there may be a delay between the time the request is canceled and the next check is performed in the Run method):

-7.1.1 interrupts

One important problem with the cancellation method above is that if a blocking method, such as Blockingqueue.put, is called in the task, the task may never check the cancellation flag and therefore never end. Like what:

As mentioned in the fifth chapter, the methods of some special blocking libraries support interrupts. A thread break is a mechanism by which a thread can notify another thread, telling it to stop the current work as appropriate or possible, and to perform other tasks instead.

Blocking method libraries, such as Thread.Sleep and object.wait, will check when a thread is interrupted and return early when an outage is found.

The following resolves an issue where the flag bit could never be checked before Brokenprimeproducer: use interrupts instead of a Boolean flag to request cancellation

-7.1.2 Interrupt Policy

* For code that is not a thread owner (for example, any code other than the thread pool implementation), you should carefully save the interrupt state so that the code that owns the thread can respond to the interrupt.

* Most blocking library function knowledge throws interruptedexception as an interrupt response, exits the process as quickly as possible, and passes the interrupt information to the caller, so that the upper code in the call stack can take further action.

* When an interrupt request is checked, the task does not need to discard all operations-it can defer processing of the interrupt request until a more appropriate moment. Therefore, you need to remember the interrupt request and either throw interruptedexception after the current task is complete or indicate that an interrupt request has been received.

-7.1.3 Response Interrupt

For some operations that do not support cancellation but can still invoke interrupts, they must call these methods in the loop (the Interrput method) and retry after the discovery of the interrupt. In this case, you should save the break state locally and restore the state before returning, rather than recovering the state when capturing Interruptedexception:

This part is a bit of a sight to understand ... First pass, and then come to delve into

-7.1.4 Example: Timed Run

An example of running an arbitrary runnable within a specified time is given. Runs any task in the calling thread and schedules a cancel task to break it after the specified time interval is run. This resolves an issue that is thrown from the task as a check exception, because the exception is caught by the caller of the Timedrun. The following program uses the Scheduledexecutorservice. Scheduledexecutorservice timed cycle execution of specified tasks

This is a simple method, but it destroys the rule that you should understand its interrupt strategy before interrupting the thread. Since Timedrun can be called from any thread, it is not possible to know the interrupt policy of the calling thread (I seem to confuse the object of the interrupt strategy).

After the Join method returns, it checks whether an exception is thrown in the task (Task.rethrow ()) and, if there is one, throws an exception again in the Timerunde thread. The thread that performs the task has its own execution policy, and even if the task does not respond to interrupts, the time-limited method (join) can still return to its caller.

Insufficient join: Unable to know whether the execution control is returned because the thread exited gracefully or because the join was over.

PS: This section looks a bit foggy, Chinese quality is too rubbish, which day to turn over the original English book, see this piece of explanation.

-7.1.5 Cancellation via future

The last Word is God horse meaning? Drunk, the language did not learn to show that the egg hurts.

-7.1.6 handling non-disruptive blocking

In the Java library, many of the blocking methods respond to interrupt requests by early return or by throwing interruptedexception, making it easier for developers to build a task that responds to cancellation requests. However, not all blocking methods or blocking mechanisms can respond to interrupts, and the interrupt request can only set the interrupt state of the thread, except that there is no other effect. For those threads that are blocked due to non-disruptive operations, these threads can be stopped using a method similar to interrupts, but this requires that we must know the cause of the thread blocking.

-7.1.7 using Newtaskfor to encapsulate non-standard cancellations

Newtaskfor is a factory method that creates a future to represent a task and also returns a Runnablefuture interface that extends the future and runnable (with Futuretask implementation). Customizing the future of a task can change the behavior of Future.cancel. The program to demonstrate:

This part sees me a bit foggy, after brush two weeks goal time again to analyze and analyze carefully.

7.2 Stopping a thread-based service

* Applications typically create services that have multiple threads

* Applications can own services, services can have worker threads, but applications cannot have worker threads, so applications cannot stop worker threads directly.

-7.2.1 Example: Log service

There is also a need to implement a method of terminating the log thread to prevent the JVM from shutting down gracefully. The Take method can respond to interrupts, and if the log thread is modified to exit when the interruptedexception is captured, the service can be stopped simply by interrupting the log thread. However, if you just leave the log thread out, it is not a complete shutdown mechanism. This direct shutdown will lose the information that is waiting to be written to the log, and other threads will be blocked when the log is called. Another way to turn off LogWriter is to set a "requested shutdown" flag to avoid further submission of log information:

upon receipt of the shutdown request, the consumer writes all messages in the queue to the log and removes all the producers that were blocked when the log was called (How do I feel here the book and the code are not number ...) )。 However, the problem of race condition exists in this method, which makes the method unreliable. to add a reliable cancel operation to LogWriter:

-7.2.2 Close Executorservice

In complex programs, Executorservice is typically encapsulated in a higher-level service, and the service can provide its own life-cycle approach. Such as:

-7.2.3 "Poison Pill" object

Another way to turn off producer-consumer services is to use the poison pill object, which stops immediately when the object is obtained. The poison pill object ensures that the consumer completes all the work in the queue first before closing. Here's an example:

The "poison pill" object can only be used if the number of producers and consumers is known. The solutions above can be extended to multiple producers: only one poison pill object is placed into the queue by each producer, and the consumer stops only when it receives the Nproducers poison pill object.

-7.2.4 Example: Perform only one-time sub-service

The Checkmail method of the following program can be used to check new messages in parallel on multiple hosts. It creates a private executor and submits a task to each host. Then, when all mail-checking tasks are completed, close executor and wait for the end.

Executeservice provides the Shutdown method: Smooth closing of Executorservice when this method is called, Executorservice stops receiving the new task and waits for the task that has been committed (containing the commit being executed and the commit not being executed) to complete execution. When all commit tasks are completed, the thread pool is closed.

Awaittermination method: Receive timeout and timeunit two parameters for setting the timeout time and unit. When the wait exceeds the set time, it will monitor if the Executorservice is closed and return true if off, otherwise false. In general, it is used in combination with the Shutdown method.

-7.2.5 Limitations of Shutdownnow

When Executeservice is forcibly closed by Shutdownnow, it attempts to cancel the task that is being performed and returns all committed tasks that have not yet started, thereby writing the tasks to the log or saving them for later processing. However, we cannot use the usual method to find out which tasks have started but have not yet ended. This means that although Shutdownnow will return all tasks that have been committed but have not yet started (all runnable), they will not be able to return tasks that have been executed but have not yet been completed and can only be canceled . There are times when we need to know and save this state, so not only do you know which tasks haven't started, but also know which tasks are not yet complete.

The following program shows how to determine the task that is being performed during the shutdown process.

The use of Trackingexecutor is given in the WebCrawler of program listing 7-22. Web crawler work is often endless, so when the crawler shuts down, we usually want to save its state (this means to save the Web page that the program is working on), so that you can continue to work on the Web pages later when restarting.

There is an unavoidable race condition in Trackingexecutor, which produces false positives: some tasks that have been canceled have actually been completed. The reason is that the thread pool may be closed between two moments when the task executes the last instruction and the thread pool logs the task to "end." This is not a problem if the task is idempotent (the result of two executions of the task will have the same result as the execution once), otherwise this risk should be considered.

7.3 Handling non-normal thread aborts

first of all, it should be clear that the most important cause of premature thread death is runtimeexception, how to handle this abnormal thread abort to ensure thread security in multithreaded situations? In short, it takes advantage of catching exception handlers and failure notification mechanisms. The following program shows how to build a worker thread inside the online pool:

The above is an active way to resolve the exception for the check. Uncaughtexceptionhandler is provided in the thread API, which detects the end of an uncaught exception. When a thread exits because of an uncaught exception, the JVM reports the event to the Uncaughtexceptionhandler exception handler.

The most common response is to write an error message and the corresponding stack trace information to the application:

To set a uncaughtexceptionhandler for all threads in the thread pool, you need to provide a threadfactory for the Threadpoolexecutor constructor.

7.4 JVM shutdown

-7.4.1 Closing the hook

In the normal JVM shutdown, the JVM first invokes all registered shut-off hooks. This closure hook refers to a thread that is registered through Runtime.addshutdownhook but has not yet started. I can't see the back, pass ....

-7.4.2 Daemon Threads

Threads can be divided into two types: normal thread and daemon thread. In all threads created at the time the JVM starts, other threads, except the main thread, are daemons (such as the garbage collector and other threads that perform auxiliary work). When a new thread is created, the new thread inherits the daemon state of the thread that created it, so by default all threads created by the main thread are normal threads. when a thread exits, the JVM checks for other running threads, and if those threads are daemons, the JVM exits normally. When the JVM is stopped, all remaining daemons will be discarded, neither the finally code block nor the rollback stack will be executed.

You should use as few daemons as possible-there are few operations that can be safely discarded without cleaning up. In particular, performing a task that might contain I/O operations in a daemon thread would be a risky behavior.

-7.4.3 Terminator

Some resources, such as file handles or sockets, must be realistically returned to the operating system when they are not needed, rather than reclaimed by the garbage collector. To implement this functionality, the garbage collector makes special handling of which objects that define the Finalize method: After the collector releases them. Call their finalize methods to ensure that some persisted resources are freed. In most cases, you can manage resources better than finalizers by using the finally block of code and the Close method shown, so avoid using finalizers.

"Java Concurrent Programming Practical" reading notes 6--Cancel and close

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.