This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
(I know, the topic's title is not the best but I think that explaining my "problem" will make it clearer..Also, in case there's already a topic about this, please let me point to it)
I'll try to be short.
I found the classic Horse Racing code in which four horses run for 3 laps on a field. This code can provide the time each horse runs a lap and it was added the funny feature of a WaterTrough. It just gives a random time the horse uses to drink water.
This is the WaterTrough class code
So, it seems that just one horse can access this "water trough area". But, what if I would like to let 2, or 3 horses accessing the area at the same time?
Thanks in advance to whomever will help
The most straightforward is probably the Semaphore. It has a count of permissions, and will block when you try to take a permission that isn't available. So on the plus side, it lets you do pretty much what you want, on the downside, it lets you take multiple permissions or release permissions from a different thread so it could be used by evil jockeys to manipulate the system.
I am sure there is a way to do it with CountDownLatch, but nothing quite as simple as Semaphore. And I can all but guarantee there are multiple other ways of doing it but these two are what stand out to me.
Joined: Nov 15, 2013
I think I considered Semaphore but for unknown reasons I never went for it. So, i never used and tried to do something with it. Do you think it is correct?
I added both acquire() and release() into the getDrink() method. It "seems" working but I'm really not sure about...
I think you should remove the synchronized keyword from the method - that would limit access to just one, which isn't what you want. After that it looks okay, but you should test again, and keep some logging / output to track who gets to what part of the method when. And really try to hammer it (have 5, 10, 100, 1000 horses all trying to get a drink. Then put a three or four in tight loops trying to access the water and make sure they all get a chance (and one horse doesn't get an unfair access to the water). Remember that we are in Computer Science - and in science there is always a lot of tests and observation happening!
Joined: Nov 15, 2013
Yeah, you're right. I forgot to remove it on the code I posted here but I did on the one I compiled. It seems it works fine now. I tried adding more and more horses (up to 100) as well as for adding "seats" (or whatever kind of word fits for it) in the watertrough and it seems working...but, as you rightly suggested, I need to experiment more and do some checkings!
Thanks for your help!