Executors in the Middle Ages |
Callable
and Future
to demonstrate the concurrency libraries in Java.In the example, I use a
ExecutorService
with a fixed thread pool size of two (2), to make the code slower to demonstrate the point. You can manipulate the value to see the effect on the code execution.The code is to demonstrate you can do it, there may be other cleaner ways of doing this. If you have an example, or idea on how to do it cleaner, please comment. :-)
Solution
The code for the project was developed using NetBeans and can be downloaded from Bitbucket at the link below. It is a NetBeans (Apache Ant) based project and should work with Ant without NetBeans.CallOrderCancel
CallOrderCancel.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | package com.bluelotussoftware.example.concurrency; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; /** * * @author John Yeary * @version 1.0 */ public class CallOrderCancel { private static final ExecutorService es; static { es = Executors.newFixedThreadPool( 2 ); } static List<Future<string>> futures = new ArrayList<>(); /** * @param args the command line arguments * @throws java.lang.InterruptedException * @throws java.util.concurrent.ExecutionException */ public static void main(String[] args) throws InterruptedException, ExecutionException { Collection<Callable<string>> callables = new ArrayList<>(); for ( int i = 0 ; i < 15 ; i++) { callables.add( new MyCallable(i)); } for (Callable<String> cx : callables) { futures.add(es.submit(cx)); } Thread.sleep( 1000 ); for (Future<string> f : futures) { if (!f.isDone()) { f.cancel( true ); System.out.println( "Cancelled... " + f.isCancelled()); } else { System.out.println( "message -> " + f.get()); } } es.shutdown(); } static class MyCallable implements Callable<string> { private final int id; public MyCallable( int id) { this .id = id; } @Override public String call() throws Exception { String message = "Callable ID: " + id + " count:" ; AtomicInteger ctr = new AtomicInteger(); synchronized ( this ) { while ( true ) { wait( 100 ); if (ctr.incrementAndGet() == 5 ) { break ; } } } return message + " " + ctr.get(); } } } |
0 comments :
Post a Comment