ParallelGamePlayer

The ParallelGamePlayer class implements the Player interface that defines the play method:

@Override 
public void play() {
Table table = new Table(NR_COLUMNS, manager);
Secret secret = new RandomSecret(manager);
Guess secretGuess = secret.createSecret(NR_COLUMNS);
Game game = new Game(table, secretGuess);
final IntervalGuesser[] guessers = createGuessers(table);
startAsynchronousGuessers(guessers);
final Guesser finalCheckGuesser = new UniqueGuesser(table);
try {
while (!game.isFinished()) {
final Guess guess = guessQueue.take();
if (finalCheckGuesser.guessMatch(guess)) {
game.addNewGuess(guess);
}
}
} catch (InterruptedException ie) {

} finally {
stopAsynchronousGuessers(guessers);
}
}

This method creates a Table, a RandomSecret that creates the guess used as a secret in a random way, a Game object, IntervalGuessers, and a UniqueGuesser. The IntervalGuessers are the bureaucrats; the UniqueGuesser is the boss who crosschecks the guesses that the IntervalGuessers create. The method starts off the asynchronous guessers and then reads the guesses in a loop from them and puts them on the table if they are OK until the game finishes. At the end of the method, in the finally block, the asynchronous guessers are stopped.

The start and the stop method for the asynchronous guessers use ExecutorService.

private ExecutorService executorService; 

private void startAsynchronousGuessers(
IntervalGuesser[] guessers) {
executorService = Executors.newFixedThreadPool(nrThreads);
for (IntervalGuesser guesser : guessers) {
executorService.execute(guesser);
}
}

private void stopAsynchronousGuessers(
IntervalGuesser[] guessers) {
executorService.shutdown();
guessQueue.drainTo(new LinkedList<>());
}

The code is quite straightforward. The only thing that may need mention is that the queue of the guesses is drained into a collection that we do not use afterward. This is needed to help any IntervalGuesser that is waiting with a suggested guess in hand, trying to put it into the queue. When we drain the queue, the guesser thread returns from the method put in the guessQueue.put(guess); line in IntervalGuesser and can catch the interrupt. The rest of the code does not contain anything that would be radically different from what we have already seen and you can find it on GitHub.

The last question that we still want to discuss in this chapter is how much speed did we gain making the code parallel?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.62.168