I have programmed sudoku in Java for homework and am currently trying to figure out the problems that it might run into to make it better. I have created several thousand sudoku nets using the David Bau sudoku generator , and now I am running my program against them.
The problem is that although most of them end in very reasonable times, some of them turn out to be problematic and make my search algorithm crazy until I exit the heap. Therefore, I thought that I should leave the work of deciding on a secondary thread and start it with a timeout. Right now I am using the thread pool of one thread (in the form of an ExecutorService ), and I am sending it Callable . Then I try to get the timeout value:
Callable<Long> solveAndReturnTime = new Callable<Long>() { }; Future<Long> time = executor.submit(solveAndReturnTime); try { long result = time.get(10, TimeUnit.SECONDS); System.out.printf("%d millis\n", result); } catch (TimeoutException e) { System.err.println("timed out"); time.cancel(true); }
My problem is that apparently one doesnโt just cancel Future in Java. Future<T>.cancel(boolean) does not seem to interrupt the task immediately. Because of this, the pool is stuck in the transfer of an undying task and the subsequent timeout of attempts, because they will never have a chance to start.
Adding more threads to the pool is not an option, because I run on limited cores and, if there are too many tasks, work hard, the legitimate ones will be unjustly slowed down. I also do not want the overhead to be frequently checked to see if the task was aborted from my main algorithm.
How can I suddenly, mercilessly and brutally end a task? I am open to anything that will allow me to restore the main thread.
EDIT My algorithm is completely consistent, does not use a global object, and does not contain a lock. As far as I can tell, nothing will go wrong if the task is canceled at a random moment; and even if so, this is not production code. I am ready to go through a dangerous and treacherous walk for this.