I am not very clear on concept of semaphores in Java and trying to understand it.
My understanding after reading oracle docs (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html) and some other pages, its similar to a lock with a count of number of permits.
It is usually used to create pools of resources. Here I get confused, there is also ThreadPoolExecutor which can give me a pool of threads. So what is the difference? Which one is used in what scenario?
Semaphore is used to restrict the number of threads that can access a resource. That is, while synchronized allows only one thread to aquire lock and execute the synchonized block / method, Semaphore gives permission up to n threads to go and blocks the others.
A Semaphore in Java controls access to a shared resource through a counter. It is a thread synchronization construct used to send signals between threads to avoid missed signals or guard a critical section.
CountDownLatch is used to start a series of threads and then wait until all of them are complete (or until they call countDown() a given number of times. Semaphore is used to control the number of concurrent threads that are using a resource.
A mutex is an object. Semaphore is an integer variable. Function. Mutex allows multiple program threads to access a single resource but not simultaneously. Semaphore allows multiple program threads to access a finite instance of resources.
First of all, there is not such thing as stupid question...
Semaphore allows multiple threads to "acquire" a resource. They should check if the resource is available. It's like a valve for flow control.
A Lock is for exclusive access. Only one thread at a time.
A ThreadPoolExecutor allows you to run some code (Runnable or Callable class) using a bounded amount of threads. You don't have to bother about building this yourself, it is already implemented for you in the JSE API. You could do your own with some semaphores and queues... but if you do not have a good reason do not waste your time.
Imaging you have to implement a web server that receives some request to port 80. You do not want to use the same thread that is listening this port to process the whole request (this is a waste of resources...). You could use a ThreadPoolExecutor deal with the request, process it and respond to the client. ThreadPoolExecutor could be configured to take advantage of the current CPUs: optimal number of threats for this architecture and this task.
Concurrency in practice is a nice book to improve your knowledge on this matter.
I hope this help you and sorry for my basic English.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With