Pages

Thursday, July 24, 2008

Solving the timing issue - Overkill?

So after sleeping on the problem, I came up with a solution. I need to touch the latch after the task has been done.
private Future makeMove(final Player player, final int round, final CountDownLatch latch, final ExecutorService executor)
{
  return executor.submit(new Callable()
    {
      public Choice call() throws Exception
      {
        try
        {
          Choice result = player.brain.makeMove(round);
          gameEventListener.moveMade(player, result);
          return result;
        }
        finally
        {
          executor.execute(new Runnable()
            {
              public void run()
              {
                latch.countDown();
              }
            });
        }
      }
    });
}
The trick is that I need finer control over the executer.
ExecutorService p1Executor = Executors.newFixedThreadPool(1, new DaemonThreadFactory());
ExecutorService p2Executor = Executors.newFixedThreadPool(1, new DaemonThreadFactory());
The reason I need an ExecutorService for each player is that when the first player finishes their moves, when the second player submits the “hit latch” task, it is possible that task gets executed and finished before the current task ends.

So I can finally access the get method with a 0 wait time: return future.get(0, TimeUnit.NANOSECONDS);.
I need some input though:
Is this overkill?
Is this ugly?
My first thought was that it gets the job done in very few, readable lines. So no.

No comments:

Post a Comment