Monday, April 19, 2010

How to implement BeerPool through counting semaphore?

No. I am not going to write code here. Drawing class diagram is also tough here. So let me list down the requirements and solution through text as much as possible.

1. It should always have the minimum beer bottles in the initialized state. i.e filled state.
2. Beer bottles should not exceed the maximum count.
3. Beer bottles should be reused (irrespective of whether they are cleaned or not)

Now one way of doing the same is listed below

A skeleton of the code is given below

public class BeerPool
{
public BeerPool getInstance()
public BeerBottle getBeerBottle()
private BeerBottle createBeerBottle()
public BeerBottle freeBeerBottle()
}

Let me maintain an integer createdBeerCount that takes care of the number of created beer bottles. getBeerBottle and freeBeerBottle methods are synchronized where you will be incrementing and decrementing counting semaphore.

LinkedList is used to maintain the BeerBottles. In getBeerBottle() method, we will use pop method of the LinkedList and return that object.

IMPORTANT: point to note here is removeElementAt(0), is O(1) operation. If createdBeerBottleCount is >= maxBeerBottleCount, thread has to wait. On interruption throw timeout exception.

Now on freeBeerBottle() method, reduce the count, and push returned BeerBottle in the LinkedList as last object. This method also takes O(1) time.

Since you know the MAX_BEER_BOTTLES count, you could easily use LinkedList instead of any other collection. But the key point here is we need to add and remove elements in O(1) time.

No comments:

Post a Comment