Guest User

Untitled

a guest
Dec 16th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. public class ConcurrentPuzzleSolver<P, M> {
  2. private final Puzzle<P, M> puzzle;
  3. private final ExecutorService exec;
  4. private final ConcurrentMap<P, Boolean> seen;
  5. protected final ValueLatch<PuzzleNode<P, M>> solution = new ValueLatch<PuzzleNode<P, M>>();
  6.  
  7. public ConcurrentPuzzleSolver(Puzzle<P, M> puzzle) {
  8. this.puzzle = puzzle;
  9. this.exec = initThreadPool();
  10. this.seen = new ConcurrentHashMap<P, Boolean>();
  11. if (exec instanceof ThreadPoolExecutor) {
  12. ThreadPoolExecutor tpe = (ThreadPoolExecutor) exec;
  13. tpe.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
  14. }
  15. }
  16. private ExecutorService initThreadPool() {
  17. return Executors.newCachedThreadPool();
  18. }
  19. public List<M> solve() throws InterruptedException {
  20. try {
  21. P p = puzzle.initialPosition();
  22. exec.execute(newTask(p, null, null));
  23. // block until solution found
  24. PuzzleNode<P, M> solnPuzzleNode = solution.getValue();
  25. return (solnPuzzleNode == null) ? null : solnPuzzleNode.asMoveList();
  26. } finally {
  27. exec.shutdown();
  28. }
  29. }
  30. protected Runnable newTask(P p, M m, PuzzleNode<P, M> n) {
  31. return new SolverTask(p, m, n);
  32. }
  33.  
  34. protected class SolverTask extends PuzzleNode<P, M> implements Runnable {
  35. SolverTask(P pos, M move, PuzzleNode<P, M> prev) {
  36. super(pos, move, prev);
  37. }
  38. public void run() {
  39. if (solution.isSet()
  40. || seen.putIfAbsent(pos, true) != null)
  41. return; // already solved or seen this position
  42. if (puzzle.isGoal(pos))
  43. solution.setValue(this);
  44. else
  45. for (M m : puzzle.legalMoves(pos))
  46. exec.execute(newTask(puzzle.move(pos, m), m, this));
  47. }
  48. }
  49. }
  50.  
  51. public class PuzzleSolver<P, M> extends ConcurrentPuzzleSolver<P, M> {
  52. PuzzleSolver(Puzzle<P, M> puzzle) {
  53. super(puzzle);
  54. }
  55.  
  56. private final AtomicInteger taskCount = new AtomicInteger(0);
  57.  
  58. protected Runnable newTask(P p, M m, PuzzleNode<P, M> n) {
  59. return new CountingSolverTask(p, m, n);
  60. }
  61.  
  62. class CountingSolverTask extends SolverTask {
  63. CountingSolverTask(P pos, M move, PuzzleNode<P, M> prev) {
  64. super(pos, move, prev);
  65. taskCount.incrementAndGet();
  66. }
  67.  
  68. public void run() {
  69. try {
  70. super.run();
  71. } finally {
  72. if (taskCount.decrementAndGet() == 0)
  73. solution.setValue(null);
  74. }
  75. }
  76. }
  77. }
Add Comment
Please, Sign In to add comment