Pages

Thursday, August 7, 2008

Dynamic instanceof?

Just came across an interesting line that I thought was worth sharing.
[java]
public static boolean isInterfaceOf (Object o, Class interfac) {
return interfac.isAssignableFrom(o.getClass());
}


Now java obviously has a instanceof keyword that allows you to do this, shorter to type and more recognisable.
The project I’m having a peek at (Archimedes an open source CAD program) only has one use for this where instanceof couldn’t work.
It hides the collection of objects and you can get all of the objects of a certain type. You could get around this by exposing the collection.

Just thought that this method actually makes the coding longer than what it actually does.

Sunday, July 27, 2008

When people fail


An alternate route must be found.

I got such a laugh out of this one.

Just make sure you read grog free and not free grog :D

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.

Wednesday, July 23, 2008

Java Out of Order

So I've got a fairly consistant output now, and its the out of order or "optimisations" being made that I think have screwed me over.
Not really a gotcha, it's just I let him sneak up on me.
return executor.submit(new Callable()
  {
    public Choice call() throws Exception
    {
      try
      {
        Choice result = player.brain.makeMove(round);
        gameEventListener.moveMade(player, result);
        return result;
      }
      finally
      {
        latch.countDown();
      }
    }
  });
Now I don’t think there should be anyway that the latch.countDown(); could be re-ordered to come before the makeMove().
This allows me to get the result of the Futures with a very small wait: return future.get(1, TimeUnit.NANOSECONDS);.
But it still isn’t instant. My problem now being that the Future isn’t being set with the result in time. If you look at it from the other side, I’m not really hooking into the right part of the Future. I really need to trigger the countDown() after the future has been finished. The Callable interface doesn’t have any other methods I can hook into and my first search of the package leaves no leads.
At least I’m a little bit happier.

Tuesday, July 22, 2008

More Rock Paper Scissors

Long long ago, I wrote an Interface for people to write Rock Paper Scissors Bots.
We were playing around with them on one open day, I can’t believe that I didn’t blog about it.
Anyway, to distract me from my actual project, I’ve started working on it again, simplifying code and extracting out interfaces with the intention of providing more that one way to join in the tournament (which is currently only if you are specified in code).
IRC seems like a perfect alternative.
One of my first challanges was how to ask two bots for their choices, but only give a limited time before giving up. It would be cool to let humans play as well so my limit is 10 seconds at the moment. The reason I have to ask two bots at once is that I don’t want to ask bot 1, wait at most 10 seconds, then ask bot 2. Both of these can be done at once.

So, using the java.util.concurrent package, I whip up an ExecutorService. The problem with the Executors.defaultThreadFactory() is that when the program ends, those threads from the factory prevent the application from ending.
That’s easy enough to fix:
class DaemonThreadFactory implements ThreadFactory
{
  ThreadFactory impl = Executors.defaultThreadFactory();

  public Thread newThread(Runnable r)
  {
    Thread t = impl.newThread(r);
    t.setDaemon(true);
    return t;
  }
}

Now, I need to wait on two different threads, sounds like a semaphore, or a CountDownLatch in Java. I pass the latch to the Callable that will be done in the other thread.

executor.submit(new Callable()
{
  public Choice call() throws Exception
  {
    Choice result = player.brain.makeMove(round);
    latch.countDown();
    gameEventListener.moveMade(player, result);
    return result;
  }
});

Then it is just a matter of CountDownLatch.await(long timeout, TimeUnit unit)

When you submit a task to the ExecutorService, you get back a Future object which can be check if the task is done and what the result of the Callable was.

future.get(2, TimeUnit.MILLISECONDS);

And this is where the fun begins.

You’ll note that I am waiting 2 milliseconds to get the value, after waiting at most 10 seconds from the latch. I know that the methods were completed because the event “moveMade” was raised.
But sometimes, just sometimes, they get call timesout.

When I was working with Threading in Advanced .Net, I was happy debugging this sort of code because all of the utility methods were my own. I wrote them, I should know what is going on. Here I am just going off the API.

Time to “Mind Meld” with the source code of the FutureTask me thinks. It seems like there is a missing synchronized keyword somewhere but I would have thought that the FutureTask would have taken care of that for me.
I’m almost putting money on there being a “Gotchas” post being made after this one.

Monday, June 30, 2008

Wander down to Warrnambool

So I went away for the weekend. Something the family hasn’t done in a while.
Went down to Warrnambool just to see if we could come across some whales.
I borrowed a friends camera for the occasion and took some shots.


Screwing around with focus:


and finally, we saw a whale.


-= Comments
1. Emma | June 29th, 2008 at 8:16 pm
HEHEHEHE… it looks like a rock. Nice photos though

2. jay | June 30th, 2008 at 5:44 pm
nice whale

Tuesday, June 3, 2008

6 month review

Sunday marked 6 months of unemployment/self-employement/holidays.
I feel it is important that you get reviewed and get a feel on how you are going at least every 6 months. 3-4 months was working very well when I was working. Since I only really report my progress to this website, I guess this is where I should do my review.

December - Was really just about me. Unwinding, playing around and catching up on things I had missed out on.
January - Was filled with a holiday, some new toys and generally consuming time with no goals (Except for the purchase of a 4wd).
February - Finally got my car so spent a bit of time cleaning it up, getting it on the road and getting to know the car. I could actually feel time slipping away from me at this point so I bought a diary and started recording what I did with each day.
March - The website project started to have some visible functionality. I was still spending too much time playing games. With my diary as reference, I started to notice that I didn’t spend much time at all on the developement. This was also when I bought my eee, so I was playing with that a fair bit.
April - I think I spent far too much conceptualising what I wanted to achieve rather than just implementing and throwing away if it didn’t work.
May - I moved away of developing on my laptop to on my desktop. When I started the “dream” I thought I would dev on my laptop most of the day, away from games, IM, emails etc. But I installed openTTD which can just suck the time out of a day. I also missed casually chatting to some people and keeping up with what is going on. After this, I started spending a lot more full afternoons on coding because I had read slashdot, I knew I had no emails and I knew that no-one was playing games. Although I have lost some days when something interesting was on slashdot, or a new upfate for a game came out .

I mentioned that I bought a diary because the days seemed to slip away. It definitely helped slow the weeks. But after reviewing six months like I have, I don’t think I’ve achieved all that much.

One of my goals 6 months ago was to get the site I am working on ready about March/April and have it up running with some users in May/June to see whether it is worth continuing as a project. I am a little dissapointed that I haven’t got the site built by this time but am not going to give up on it just yet.

I see my 2 problems as sleeping in and motivation.
I really need to get back to working on the project at standard hours, say 9-5. At the moment I am waking up at 12:00, having lunch, reading news and then being ready to code between 2-3:00pm. Then there is 2-3 hours of code before people start jumping online and playing games.
Motivation is a little more tricky to work out because I don’t know what motivated me whilst I had a job. It was just a routine I did on weekdays (which could be a reason why I quit). Maybe it is because I’m working on a dull part of the site at the moment. I plan to implement the storage engine with a Java Content Repository but because the tools to integrate with it are currently ‘in developement’, I’ve sort of held off. I’ve considered buying a Wii as a sort of reward for getting to a milestone like implementing the storage engine in a JCR, but the Wii would just be another thing to distract me from coding.

One thing I don’t have is a task tracking tool whilst working on the project to give me feedback on how close I am to completing a stage. A while ago I decided that I should try to break the project up into stages I want to achieve.

  • 0.1 - Working front end with dummy, in memory back end

  • 0.2 - Change back end to be persistant

  • 0.3 - Give the site a fair skin. (I don’t think pure css will cut it)

  • 0.4 - Review, Check that it will handle at least some load. Probably a closed beta so I can get other people to check bugs and comment on skin

  • 0.5 - Working release. The project is to help 2 groups of people connect. I need to get a minimalistic site going and see what people think and find out what they want next


Done, now where is my IDE…..

-= Comments
1. Tim Rowe | June 2nd, 2008 at 6:32 pm
Wait, you’ve spent *six months* unemployed!?
Holy crap dude. Why??

2. pimaster | June 2nd, 2008 at 10:13 pm
Have you missed the parts of the blog that relate to me starting my own project?
I wanted to do my own thing whilst working for Hyro, but it becomes too time consuming to do both at once.
Following a dream is important.
I think it is important that I tackle a whole project on my own to improve what I can bring to a team environment.
It may also give me a chance to give back to some open source projects. Something I could have done at my old job, but not under my own pacing.
Most importantly, because I can.

3. Xavier | June 3rd, 2008 at 2:11 pm
“Wait, you've spent *six months* unemployed!?
Holy crap dude. Why??”

You’ve got this around the wrong way. If you’ve been employed for 6 months you better have a damn good reason.

It’s like when people ask ‘why are you vegan?' Worrong question. Why are you not?