Java concurrency (specific instance)-several examples
This section simulates a simple page rendering function, which is used to draw HTML pages to the image cache for convenience, assume that the HTML file only contains the label text and the image and URL of the reserved size. 1. The simplest implementation of the serial page Renderer is to perform serial processing on HTML documents: first draw the text, then draw the image, and then perform serial processing: public class SingleThreadRenderer {void renderPage (CharSequence source) {renderText (source); List <ImageData> imageData = new ArrayList <ImageData> (); for (ImageInfo imageInfo: scanForImageInfo (source) imageData. add (imageInfo. downloadImage (); for (ImageData data: imageData) renderImage (data) ;}} this implementation method has a problem, because most of the time the image download process is waiting for the completion of the I/O operation, during which the CP U does almost no work. Therefore, this execution method does not fully utilize the CPU, so that the user has to wait too long before seeing the final page. By decomposing the problem into multiple independent tasks for concurrent execution, the system can improve CPU utilization and response sensitivity. 2. Use Future to implement the page Renderer. In order to make the page Renderer more concurrent, the rendering process is first divided into two tasks. One is to render all the text, the other is to download all the images (CPU-intensive and I/O-intensive ). Callable and Future help to represent the interaction of such collaborative tasks. The following code first creates a Callable to download all the images. When the director needs the image, it will wait for the call result of Future. get. If you are lucky, the image may have been downloaded, even if not, at least it has been downloaded in advance. Public class FutureRenderer {private final ExecutorService executor = Executors. newCachedThreadPool (); void renderPage (CharSequence source) {final List <ImageInfo> imageInfos = scanForImageInfo (source ); callable <List <ImageData> task = new Callable <List <ImageData> () {public List <ImageData> call () {List <ImageData> result = new ArrayList <ImageData> (); for (ImageInfo imageInfo: imageInfos) resul T. add (imageInfo. downloadImage (); return result ;}}; Future <List <ImageData> future = executor. submit (task); renderText (source); try {List <ImageData> imageData = future. get (); for (ImageData data: imageData) renderImage (data);} catch (InterruptedException e) {Thread. currentThread (). interrupt (); future. cancel (true);} catch (ExecutionException e) {throw launderThrowable (e. getCause () ;}} Of course We can also optimize it. users do not need to wait for all the images to be downloaded. We can immediately display each downloaded image. 3. Use CompletionService to implement the page Renderer and draw the image immediately after the download is completed. We need to know in time that the image download is complete. In this scenario, CompletionService is very suitable. CompletionService separates the production of new asynchronous tasks from the use of the results of completed tasks. The tasks executed by the producer submit. The user takes completed tasks and processes their results in the order they are completed. The following code uses CompletionService to rewrite the implementation of the page Renderer: public abstract class Renderer {private final ExecutorService executor; Renderer (ExecutorService executor) {this.exe cutor = executor;} void renderPage (CharSequence source) {final List <ImageInfo> info = scanForImageInfo (source); CompletionService <ImageData> completionService = new ExecutorCompletionService <ImageData> (executor); for (final ImageInfo imageInfo: Info) completionService. submit (new Callable <ImageData> () {public ImageData call () {return imageInfo. downloadImage () ;}}); renderText (source); try {for (int t = 0, n = info. size (); t <n; t ++) {Future <ImageData> f = completionService. take (); ImageData imageData = f. get (); renderImage (imageData) ;}} catch (InterruptedException e) {Thread. currentThread (). interrupt ();} catch (executionfailed t Ion e) {throw launderThrowable (e. getCause () ;}}set the time limit for a task. Sometimes, if a task cannot be completed within the specified time, the result is no longer needed. In this case, you can discard the task. For example, a Web application obtains advertisement information from an external advertisement server, but if the application does not receive a response within two seconds, a default advertisement page is displayed, in this way, even if the advertisement information cannot be live, the site's response performance will not be reduced. For this demand, Future. the get method can be implemented: Page renderPageWithAd () throws InterruptedException {long endNanos = System. nanoTime () + TIME_BUDGET; Future <Ad> f = exec. submit (new FetchAdTask (); // Render the page while waiting for the ad Page page = renderPageBody (); Ad ad; try {// Only wait for the remaining time budget long timeLeft = endNanos-System. nanoTime (); ad = f. get (timeLeft, NANOSECONDS);} catch (ExecutionException e) {ad = DEFAULT_AD;} catch (TimeoutException e) {ad = DEFAULT_AD; f. cancel (true);} page. setAd (ad); return page;} This "reservation time" method can easily be extended to any number of tasks, consider such a travel website: users enter travel dates and requirements, and the website can obtain results through multiple channels. At this time, the page response time should not be limited by the slowest way, instead, we should only display the messages received within the specified time. We can submit multiple tasks to one ExecutorService by using invokeAll that supports the limited time: public class TimeBudget {private static ExecutorService exec = Executors. newCachedThreadPool (); public List <TravelQuote> getRankedTravelQuotes (TravelInfo travelInfo, Set <TravelCompany> companies, Comparator <TravelQuote> ranking, long time, TimeUnit unit) throws InterruptedException {List <QuoteTask> tasks = new ArrayList <QuoteTask> (); for (TravelCompany company: companies) tasks. add (new QuoteTask (company, travelInfo); List <Future <TravelQuote> futures = exec. invokeAll (tasks, time, unit); List <TravelQuote> quotes = new ArrayList <TravelQuote> (tasks. size (); Iterator <QuoteTask> taskIter = tasks. iterator (); for (Future <TravelQuote> f: futures) {QuoteTask task = taskIter. next (); try {quotes. add (f. get ();} catch (ExecutionException e) {quotes. add (task. getFailureQuote (e. getCause ();} catch (CancellationException e) {quotes. add (task. getTimeoutQuote (e) ;}} Collections. sort (quotes, ranking); return quotes;} class QuoteTask implements Callable <TravelQuote> {private final TravelCompany company; private final TravelInfo travelInfo; public QuoteTask (TravelCompany company, TravelInfo travelInfo) {this. company = company; this. travelInfo = travelInfo;} TravelQuote getFailureQuote (Throwable t) {return null;} TravelQuote getTimeoutQuote (CancellationException e) {return null;} public TravelQuote call () throws Exception {return company. solicitQuote (travelInfo);} interface TravelCompany {TravelQuote solicitQuote (TravelInfo travelInfo) throws Exception;} interface TravelQuote {} interface TravelInfo {}