Java.util.concurrent.Future Basics

Source: Internet
Author: User

Hereby I am starting a series of articles about the future concept in programming languages (also known as promis Es or delays) with a working title: back to the future. Futures is very important abstraction, even more these day than ever due to growing demand for asynchronous, Eve Nt-driven, parallel and scalable systems. In the first article we'll discover most basic java.util.concurrent.Future<T> interface. Later on we'll jump to other frameworks, libraries or even languages. is Future<T> pretty limited, but essential to understand, EKHM, the future parts.

In a single-threaded application if you call a method it returns only when the computations is done ( IOUtils.toString() comes from a Pache Commons IO):

Downloadcontents (IOException {
    Try (URL.  OpenStream ()) { 
        Ioutils. toString (standardcharsets.  Utf_8);  
    }
}
//...
Downloadcontents (URL ("http://www.example.com")); 

downloadContents()Looks harmless1, but it can take the even arbitrary long time to complete. Moreover in order-to-reduce latency you might want to does other, independent processing in the meantime, while waiting for Results. Would start a new Thread and somehow wait for results (shared memory, locks, dreadful wait() / notify() PA IR, etc.) With Future<T> it ' s much more pleasant:

Future<Stringstartdownloading (url) {   
    //...
}
Future<Stringstartdownloading (URL ("http://www.example.com"));    
Other computation
Contentsfuture. get ();

We'll implementstartDownloading()Soon. For now it's important that understand the principles.startDownloading()Does notblock, waiting for external website. Instead it returns immediately, returning a lightweightFuture<String>Object. This object is aPromiseThatString'll is available in the future. Don ' t know when, but keep this reference and once it's there, you'll be able to retrieve it usingFuture.get(). In other wordsFutureis a proxy or a wrapper around an object, which is not yet there. Once the asynchronous computation is do, you can extract it. So-what API doesFutureProvide?

Future.get()Is the most important method. It blocks and waits until promised result is available (Resolved). So if we really need thatString, Just callget()and wait. There is a overloaded version that accepts timeout so won ' t wait forever if something goes wild.TimeoutExceptionis thrown if waiting for too long.

In some with cases you might want to peek on theFutureand continue if result is not yet available. This was possible withisDone(). Imagine a situation where your user waits for some asynchronous computation and you ' d like to let him know the We are STI ll waiting and do some computation in the meantime:

Future<Stringstartdownloading (URL ("http://www.example.com"));    
while (!  Contentsfuture. IsDone ()) {
    Askusertowait ();
    Dosomecomputationinthemeantime ();
}
Contentsfuture. get ();

contentsFuture.get()guaranteed to return immediately and not block because Future.isDone() returned true . If you follow the pattern above make sure is not busy waiting, calling millions of time isDone() per second.

Cancelling futures was the last aspect we had not covered yet. Imagine started some asynchronous job and you can only wait for it given amount of time. If it ' s not there after, say, 2 seconds, we give up and either propagate error or work around it. However if you is a good citizen, you should somehow the future object:i no longer need you, forget about it. You save processing resources by not running obsolete tasks. The syntax is simple:

Contentsfuture. Cancel (true);    //meh   ...

We all love cryptic, Boolean parameters, aren ' t we? Cancelling comes in the flavours. by passingfalseTomayInterruptIfRunningParameter we only cancel tasks this didn ' t yet started when theFutureRepresents results of computation that does not even began. If ourCallable.call()It already in the middle and we let it finish. However if we passtrue,Future.cancel()'ll is more aggressive, trying to interrupt already running jobs as well. How? Think about all these methods that throw infamousInterruptedException, namelyThread.sleep(),Object.wait(),Condition.await(), and many others (includingFuture.get()). If you is blocking on any of such methods and someone decided to cancel yourCallable, they'll actually throwInterruptedException, signalling that someone are trying to interrupt currently running task.

So we are understand what

Future<T>

Is-a Place-holder for something, that's you'll get in the future. It's like the keys to a car the is not yet manufactured. Actually obtain an instance of

Future<T>

In your application? The most common sources is thread pools and asynchronous methods (backed by thread, pools for you). Thus our

startDownloading()

Method can is rewritten to:

Executors. Newfixedthreadpool (ten); 
Future<Stringstartdownloading (ioexception {   
    Pool. Submit (callable<String> () {    
        @Override
        Exception {
            Try (URL.  OpenStream ()) { 
                Ioutils. toString (standardcharsets.  Utf_8);  
            }
        }
    });
}

A lot of syntax boilerplate, but the basic idea was simple:wrap long-running computations in

Callable<String>

and

submit()

them to a thread pool of ten threads. Submitting returns some implementation of

Future<String>

, most likely somehow linked to your task and thread pool. Obviously your task is not executed immediately. Instead It is placed in a queue which are later (maybe even much later) polled by thread from a pool. Now it should is clear what these-flavours of

cancel()

Mean-you can always cancel task the still resides in the that queue. But cancelling already running task was a bit more complex.

Another place where can meet

Future

is Spring and EJB. For example in the Spring framework you can simply annotate your method with @Async :

@Async
Future<Stringstartdownloading (ioexception {   
    Try (URL.  OpenStream ()) { 
        AsyncResult<> (
                Ioutils. toString (standardcharsets.  Utf_8)  
        );
    }
}

Notice that we simply wrap our result in AsyncResult implementing

Future

. But the method itself does isn't deal with thread pool or asynchronous processing. Later on Spring would proxy all calls to

startDownloading()

and run them in a thread pool. The exact same feature is available through @Asynchronous annotation in EJB.

So we learned a lot of about

java.util.concurrent.Future

. Now it's time to admit-this interface are quite limited, especially when compared to other languages. More on that later.

Java.util.concurrent.Future Basics

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.