If you have a resource that only once person should access at a time you could use a semaphore of size one or you could just use a single ReentrantLock instance?
What are the subtle difference that make one or the other the better decision?
There are differences:
Semaphore
s are good for counting permits/releases, so if you have more than one resource, Lock
etal. will not help you much. But if you have only one resource to guard, they are good enough.
Counting Semaphore Example: You have a protected object, with a restriction of not more than five threads are allowed to access it concurrently. In that case a counting semaphore of initial value 5 is the mathematical fit. Downey's Little book of Semaphores is one of the best reads to understand the constructs.
While it is true that this can be done with both synchronized
and Semaphore
you first must figure out how you will use this resource. If you use synchronized
this means that you will have to watch on synchronization in threads:
public void run() {
// some code
synchronized (resource) {
// use resource
}
}
If you don't want to let threads watch for this (which is in my opinion better), use Semaphore
in getter method of resource:
public Resource acquireResource() {
// acquire semaphore
return resource;
}
public void releaseResource() {
// release semaphore
}
and in thread just do:
public void run() {
// some code
Resource resource = ResourceContainer.getResource();
// do something with resource
releaseResource();
}
You can add Object
parameter to these methods just to compare if same object released semaphore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.