At a golf club, players can hire golf balls for their game from the club and return them to the club after use. The better players, who tend not to lose any balls, only hire one or two. The less experienced players hire more balls, so that they will have spares during the game in case of loss. They are, however, required to buy replacements for the lost balls so that they return the same number that they originally hired. The golf balls are kept by the club groundsman, who turns out to be a techie. He decides to treat the players as Java threads and to write a monitor to allocate golfballs to players, if available, or to delay the players if insufficient are available.
However, with our simple allocation policy, it is possible that a player with many balls may starve. Try two players with 4 and 5 balls, then make many players with one and two balls. As you see, the (later) players with few balls get served, whereas the (early) players that need many balls are not served.
Subclass the class GolfClub
and overwrite the template method buildAllocator
so that the club
uses different allocation policies. Implement a fair policy (e.g. FairAllocator.java)
that does not allow players to starve. Allocators must implement the interface
IAllocator.java.
Hint: A simple fair solution would be: 'first come, first served'
Here are possible solutions.