Java concurrent programming task cancellation (6)

Source: Internet
Author: User

Java concurrent programming task cancellation (6)
Disable ExecutorService

ExecutorService provides two methods to shut down normally, and ShutdownNow is used to force the Shutdown. During forced shutdownNow, shutdownNow first closes the current task. Return to the list of all tasks that have not been started.

The returned method is not clear when the list of unstarted tasks is returned, so I checked the source code.

    /**     * Attempts to stop all actively executing tasks, halts the     * processing of waiting tasks, and returns a list of the tasks     * that were awaiting execution.     *     * 

This method does not wait for actively executing tasks to * terminate. Use {@link #awaitTermination awaitTermination} to * do that. * *

There are no guarantees beyond best-effort attempts to stop * processing actively executing tasks. For example, typical * implementations will cancel via {@link Thread#interrupt}, so any * task that fails to respond to interrupts may never terminate. * * @return list of tasks that never commenced execution * @throws SecurityException if a security manager exists and * shutting down this ExecutorService may manipulate * threads that the caller is not permitted to modify * because it does not hold {@link * java.lang.RuntimePermission}{@code ("modifyThread")}, * or the security manager's {@code checkAccess} method * denies access. */ List shutdownNow();


Returns the Runnable of the submit in the form of List.


Use Log service as a chestnut as in the previous article.

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.TimeUnit;public class LogService {private final ExecutorService exec = Executors.newSingleThreadExecutor();private final int TIMEOUT = 100;...public void start() {}public void stop() throws InterruptedException {try {exec.shutdown();exec.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS);} finally {writer.close();}}public void log(String msg){try{exec.execute(new writerTask(msg)));}catch(RejectedExecutionException ignored){}}}
Some code is omitted. Because it is the same as the code in the previous article, it mainly shows how it looks after the Stop method after ExecutorService is used

Drug pill object

This is another kind of consumer's Chestnut. Poison pills refer to an object put on the queue and its function is to stop immediately when this object is obtained. In a FIFO queue, the poison pill object ensures that the consumer completes all work in the queue before closing.

For example... Oh .. Debugging takes a long time ..

Import java. io. file; import java. io. fileFilter; import java. util. concurrent. blockingQueue; import java. util. concurrent. define blockingqueue; public class InderXingService {private static final File POISON = new File (""); private final IndexerThread consumer = new IndexerThread (); private final crawler lerthread producer = new crawler thread (); private final BlockingQueue
 
  
Queue = new LinkedBlockingQueue
  
   
(); Private final FileFilter fileFilter; private final File root = new File ("F: // Desktop/Open"); public static void main (String [] args) {InderXingService index = new InderXingService (null, null); index. start ();} public InderXingService (FileFilter fileFilter, File root) {this. fileFilter = fileFilter;} public void start () {producer. start (); consumer. start ();} public void stop () {producer. interrupt ();} public Void awaitTermination () throws InterruptedException {consumer. join ();} class crawler Thread extends Thread {@ Overridepublic void run () {// TODO Auto-generated method stubtry {crawl (root);} catch (InterruptedException e) {e. printStackTrace ();} finally {System. out. println ("putpoison"); while (true) {try {queue. put (POISON); break;} catch (InterruptedException e1) {}}} private void crawl (File root) throws InterruptedException {// Add File [] entries = root. listFiles (); if (entries! = Null) {for (File entry: entries) {if (entry. isDirectory () {crawl (entry. getAbsoluteFile ();} else if (! Alreadindex (entry) {queue. put (entry) ;}}} private boolean alreadindex (File entry) {// TODO Auto-generated method stubif (queue. contains (entry) {return true;} return false;} class IndexerThread extends Thread {@ Overridepublic void run () {while (true) {File file; try {file = queue. take (); if (file = POISON) {break;} else {indexFile (file) ;}} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} private void indexFile (File root) throws InterruptedException {System. out. println (root. getName ());}}}
  
 
This is the example of a file that traverses a directory-0-

I tried to traverse the entire fdisk just now .. It seems that the consumer is following. It seems that you can use it without any pressure.


public static void main(String[] args) {InderXingService index = new InderXingService(null, null);index.start();try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}index.stop();}
I tried the interrupt method.


UpgradeReport. xslt
UpgradeReport_Minus.gif
UpgradeReport_Plus.gif
Java. lang. InterruptedException
Putpoison
At java. util. concurrent. locks. AbstractQueuedSynchronizer. acquireInterruptibly (Unknown Source)
At java. util. concurrent. locks. ReentrantLock. lockInterruptibly (Unknown Source)
At java. util. concurrent. Define blockingqueue. put (Unknown Source)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 73)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 71)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 71)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 71)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 71)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 71)
At InderXingService $ CrawlerThread. crawl (InderXingService. java: 71)
At InderXingService $ crawler thread. run (InderXingService. java: 49)

The result is also correct.


Note the following:

The drug pill object can be used only when the number of producers and consumers is known. When there are many producers, you can add a counter and interrupt them when all the producers put their balls in the queue. When there are multiple consumers, a producer can put the same number of pills as the consumers. Because each consumer can only receive one ball. It is not easy to use when both of them are large. Only in Unbounded queues. Drug pills can work reliably.




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.