I want to implement iterative deepening (incremental tree building). This is the part of my code I will ask about:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<Integer>> callables = new HashSet<Callable<Integer>>();
callables.add(new Callable<Integer>() {
public Integer call() throws Exception {
iterativeDeepening(depthLimit, board);
return -1;
}
});
callables.add(new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(500);
return 1;
}
});
try{
executorService.invokeAny(callables, 1000, TimeUnit.MILLISECONDS);
}catch(TimeoutException | InterruptedException ex){
executorService.shutdown();
}
executorService.shutdown();
From what I read about invokeAny() with time limit it should end executing its Callable objects as soon as the deadline is reached. It works when I put long sleep instead of my function iterativeDeepening(depthLimit, board). How to make it work with my function? Below I paste the code to this function:
public void iterativeDeepening(byte depthLimit, byte[] board){
for(byte depth=1;depth<depthLimit;depth++){
GameTree gameTree= new GameTree();
byte[] tempBoard = new byte[14];
for(byte i=0;i<14;i++){
tempBoard[i] = board[i];
}
Node <byte[]> root= new Node<byte[]>(tempBoard, player);
try {
gameTree.buildGameTree(depth, root);
} catch (OutOfMemoryError E) {
gameTree.eraseGameTree(depth,root);
System.gc();
}
MiniMax minimax = new MiniMax(player);
move= minimax.selectMove(depth, root);
}
}
If you know a better way to make it or know how to successfully stop execution of my function please let me know. I tried also a Runnable Interface mentioned in this topic: How to stop execution after a certain time in Java? but it just worked the same.