I am trying to use futures for the first time. It seems smart that you can cancel a job, but it is not working as expected. In the example below, only the first job is cancelled. The rest are completed. Have I misunderstood the use of futures?
public class ThreadExample
{
public static void main(String[] args) throws InterruptedException, ExecutionException
{
int processors = Runtime.getRuntime().availableProcessors();
System.out.println("Processors: " + processors);
ExecutorService es = Executors.newFixedThreadPool(processors);
int nowork = 10;
Future<Integer>[] workres = new Future[nowork];
for(int i = 0; i < nowork; i++)
{
workres[i] = es.submit(new SomeWork(i));
}
for(int i = 0; i < nowork; i++)
{
if(i % 2 == 0)
{
System.out.println("Cancel");
workres[i].cancel(true);
}
if(workres[i].isCancelled())
{
System.out.println(workres[i] + " is cancelled");
}
else
{
System.out.println(workres[i].get());
}
}
es.shutdown();
}
}
class SomeWork implements Callable<Integer>
{
private int v;
public SomeWork(int v)
{
this.v = v;
}
@Override
public Integer call() throws Exception
{
TimeUnit.SECONDS.sleep(5);
System.out.println(v + " done at " + (new Date()));
return v;
}
}
The output:
Processors: 4
Cancel
java.util.concurrent.FutureTask@10d448 is cancelled
4 done at Wed May 12 17:47:05 CEST 2010
2 done at Wed May 12 17:47:05 CEST 2010
1 done at Wed May 12 17:47:05 CEST 2010
3 done at Wed May 12 17:47:05 CEST 2010
1
Cancel
2
3
Cancel
4
5 done at Wed May 12 17:47:10 CEST 2010
7 done at Wed May 12 17:47:10 CEST 2010
8 done at Wed May 12 17:47:10 CEST 2010
6 done at Wed May 12 17:47:10 CEST 2010
5
Cancel
6
7
Cancel
8
9 done at Wed May 12 17:47:15 CEST 2010
9