Java Reference
In-Depth Information
Listing 8.14. Link Node for the Puzzle Solver Framework.
The concurrent approach also trades one form of limitation for another that might be more
suitable to the problem domain. The sequential version performs a depth-first search, so the
search is bounded by the available stack size. The concurrent version performs a breadth-first
search and is therefore free of the stack size restriction (but can still run out of memory if the
set of positions to be searched or already searched exceeds the available memory).
In order to stop searching when we find a solution, we need a way to determine whether any
thread has found a solution yet. If we want to accept the first solution found, we also need to
update the solution only if no other task has already found one. These requirements describe
a sort of latch (see Section 5.5.1 ) and in particular, a result-bearing latch . We could easily
build a blocking resultbearing latch using the techniques in Chapter 14 , but it is often easier
and less error-prone to use existing library classes rather than low-level language mechan-
isms. ValueLatch in Listing 8.17 uses a CountDownLatch to provide the needed latch-
ing behavior, and uses locking to ensure that the solution is set only once.
Each task first consults the solution latch and stops if a solution has already been found. The
main thread needs to wait until a solution is found; getValue in ValueLatch blocks until
some thread has set the value. ValueLatch provides a way to hold a value such that only
the first call actually sets the value, callers can test whether it has been set, and callers can
Search WWH ::




Custom Search