Unlock the Mystery of the future. Cancel Mission

Source: Internet
Author: User

The application scenarios and features of the future have been mentioned in a previously written essay. (executorservice--<t> future<t> Submit (callable<t> Task))

Let's take a look at it first:

 Public classFuturecanceldemo { Public Static voidMain (string[] args)throwsinterruptedexception {executorservice exec=Executors.newcachedthreadpool (); Future<Target> future = Exec.submit (NewDemotask ()); TimeUnit.SECONDS.sleep (2);//give enough time to start up, but not enough to get it doneFuture.cancel (true); }}classTarget {//Mission Objectives}classDemotaskImplementscallable<target> {//Task    Private Static intCounter = 0; Private Final intid = counter++; @Override PublicTarget Call ()throwsException {System.out.println ( This+ "Start ..."); TimeUnit.SECONDS.sleep (5);//time required to run a simulated taskSystem.out.println ( This+ "completed!"); return NewTarget (); } @Override PublicString toString () {return"task[" + ID + "]"; }}

In general, where will we use future objects?

When we need to control the task (Runnable/callable object), we submit the task to the executor (Executorservice.submit ()) and return a control handle (future). To check the status of the task execution at some point in the future, get the results of the task execution, and cancel the task when necessary.

Today we'll see how the future cancels the task.

We know that the future is just an interface, and how does it really work for the task to be canceled?

We know that by handing over the task to the actuator, the actuator returns us to a future. But since the code is well encapsulated, the future and Executorservice are just an interface, and we only know how to use it, but we don't know how it is implemented internally. If you want to see how it is implemented, trace it to the end until you find the final implementation class. First of all, our executorservice is obtained from the factory class executors. Take the above code as an example, we get a buffer thread pool Threadpoolexecutor type of object, and Threadpoolexecutor did not rewrite the Submit method, but the implementation of its parent class, and its parent class is abstractexecutorsevice. This class provides the most basic underlying implementation of the Executorservice interface. We finally found the implementation of the Submit method.

From here we can see that the method takes runnablefuture as the return value. And the value is generated by the Newtaskfor method.

But what is the runnablefuture,futuretask,future relationship?

That is, Runnablefuture inherits the Runnable and the Future interface, which represents a controllable task. And Futuretask implements this interface. So the cancellation of the future is finally realized by this futuretask.

Let's take a look at how it implements the cancel operation (Future.cancel ()).

Obviously, if the task is already started, the method of canceling the task is to break the thread that executes it .

In this case, there may be some doubts about the Cancel parameter mayinterruptifrunning, which is what it is used for. Let's take a look at the future definition of the method.

That is, if mayinterruptifrunning is true, if the task is not started, the task status ID is modified so that the task cannot start. If it is already started, you can end the task with a policy of break thread. That is, tasks that are not started and started can be canceled.

If Mayinterruptifrunning is false, only tasks that are not started can be canceled. A task that has been started is allowed to continue execution.

Deepen your impressions with an example:

 Public classFutureCancelDemo2 { Public Static voidMain (string[] args)throwsinterruptedexception {executorservice exec= Executors.newcachedthreadpool ();//buffer thread pool Future<Target> future = Exec.submit (NewDemotask ()); TimeUnit.SECONDS.sleep (2);//give enough time to start up, but not enough to get it done        BooleanCANCELRESULT1 = Future.cancel (true);//true indicates that if it is already running, the interrupt Future<Target> Future2 = Exec.submit (NewDemotask ()); TimeUnit.SECONDS.sleep (2); BooleanCANCELRESULT2 = Future2.cancel (false); System.out.println ("CANCELRESULT1:" +CANCELRESULT1); System.out.println ("CANCELRESULT2:" +cancelResult2); Try{target target=Future2.get (); } Catch(executionexception e) {e.printstacktrace (); }    }}

Operation Result:

It is strange to see the above code and run the result. Let me share with you my doubts.

① According to the previous definition, since the task is already running, then cancel should not interrupt the task, why is the return value true?

② by Output "task[1] completed!" It is known that Task 2 has been completed. Why does Future2.get () get an error?

Answer:

I take it for granted that the return value of Cancel is considered a success flag for cancellation. Let's look at the official definition of the future interface.

That is, if the return value of Cancel is false, there are several things: the task has already been completed and a cancel has been called before, for other reasons, it cannot be canceled.

Any other situation will return true

Also, because cancel does not actually interrupt a running task, it implements a logical cancellation , that is, the modify task execution is identified as "canceled." Therefore, it is not meaningful to call the Get method again.

Let's take a look at the definition of a get operation:

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.