aspose file tools*
The moose likes Threads and Synchronization and the fly likes Why do we need semaphore? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Why do we need semaphore?" Watch "Why do we need semaphore?" New topic
Author

Why do we need semaphore?

azuki ooh
Greenhorn

Joined: Nov 07, 2008
Posts: 20
This is one of the codes I got from my textbook. Can someone help me to understand why is the sem.acquire() and sem.release() necessary when we can keep track of which item is used or unused simply using the getAvailableItem() and markAsUnused()?



>
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 416
    
    2

hi,

Does that even compile ? I'm suggesting not.

It also looks slightly bugged.


In general the semaphore could allow you to constrain concurrently a list of resources to a (different) given number concurrently in use where, also getAvailableItem in intent
would potentially give you a no none available (eg null) whereas the semaphore would wait on the concurrent users to release i.e. its a blocking call.
So getAvailableItem is a kind of try to get one of a big set of resources but immediately fail if not available but getItem is a try to get one if two many users are working wait till one finishes.

I'd suggest getting the code to compile and run it first.

"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why do we need semaphore?