import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.Math.random;
public class TestLoopInterrupt {
public static void main(String[] args) {
// Create an array with 10 calculation objects
CalculationObject[] calcObjects = new CalculationObject[10];
/* This is our for loop where we will do lengthy calculations
on a bunch calculation objects in an array. Each call to
performCalculation() will last a maximum of 20 seconds*/
for(CalculationObject o : calcObjects) {
/*Create a calculation object with some random number as an
attribute and then perform some lenghty calculations on it
and output the result */
o = new CalculationObject((double)(random()*10));
System.out.println("Number was " + o.getNum());
o = performCalculation(o);
System.out.println("Number is " + o.getNum());
}
}
private static CalculationObject performCalculation(CalculationObject o) {
/*Create an Executor that uses a single worker thread operating
off an unbounded queue*/
final ExecutorService service = Executors.newSingleThreadExecutor();
/*Create instance of our LengthyCalculation class, passing our
Calculation Object as a parameter to be used in the calculation*/
LengthyCalculation lengthyCalculation = new LengthyCalculation(o);
try {
//Use a Future to represent the result of our calculations
final Future<CalculationObject> f = service.submit(lengthyCalculation);
/*Get the result, waiting up to 20 seconds.
A TimeoutException is thrown if the calculation has not been
completed in 20 seconds.*/
o = f.get(20, TimeUnit.SECONDS);
} catch (final TimeoutException e) {
System.err.println("Calculation took to long");
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdown();
service.shutdownNow();
}
return o;
}
}