Skip to content

Instantly share code, notes, and snippets.

@mrWinston
Last active October 6, 2017 12:06
Show Gist options
  • Save mrWinston/984d71b269f7eed9a02a to your computer and use it in GitHub Desktop.
Save mrWinston/984d71b269f7eed9a02a to your computer and use it in GitHub Desktop.
Java Futures usage #java #future #concurrency #multithreading #communication
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*/
/**
* Executes Multiple futures
*
*/
public void futureRequests(){
List<Future<Object>> rawList = new ArrayList<Future<Object>>();
ExecutorService executor = Executors.newCachedThreadPool();
List<Object> results = new ArrayList<Object>();
//this.parameters is a List with the parameters for the executors
for(Object o : this.parameters){
rawList.add(executor.submit(new CustomFuture(o)));
}
for(Future<Object> futu : rawList){
try {
results.add(futu.get());
} catch (InterruptedException ex) {
Logger.getLogger(SimulationBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(SimulationBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class CustomFuture implements Callable<Object>{
Object parameter;
public CustomFuture(Object parameter) {
this.parameter = parameter;
}
@Override
public Serializable call() throws Exception {
return someLongMethodCall(this.object);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment