% trick
August 23rd, 2004 by HenA while back, we got addicted to IBM’s CodeRuler at work. It involves having a large group of objects managed by the system, and you get given a 500 millisecond gap in which to give them all orders for the next round.
A major problem is that you can’t change those objects (peasants and knights) codewise. So there’s no way to extend them, add better behaviour, or gain any access to the system’s containment for them (to split them up into subgroups for example, or even to know when new ones are created).
My solution to this was a neat trick I think. Probably well known by many, but also probably new to others. I created command-style objects that knew what each groups particular mission was. I then used the following snippet, while looping over my population of peasants to assign them to a mission each time:
peasant.hashCode() % peasantMissions.length
I did the same for my knights. It’s a nice little trick (in my opinion) that means that even though I don’t have control over the objects, I’m able to split them off into groups, and keep them in the same groups, without any extra container systems.
My previous version had Mission objects which contained the peasants, and it wasted time at the start finding the newborn peasants and adding them to the missions etc.
It came up tonight as a solution to a threading problem. We have a threadpool. It acts as the server-process for a client (much as a forked process with Apache does I think), however it is completely first-come-first-serve in which client it chooses to send a message to (this is a push system). As we’ve hooked it to a system that sends messages a lot more than before, we’re finding that the 10 threads are overtaking each other and clients are receiving the data for a single construct out of order.
So one possible solution that immediately raises itself for me is that I could apply the % trick. Effectively it gives you a repeatable load-balancer (low-tech as it is), and each client would appear to switch to a single-threaded system, even though the server was still being aggressively multi-threaded.
As I said, this is probably well known in the right circles, but I liked how a simple game environment that was largely seen as a harmless bit of fun has helped me out.
