Mutex vs semaphore in java development

Let's take a look at what the stack overflow says first

Original address: http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference

In short, mutex is exclusive. Only one resource can be obtained. Semaphore is also exclusive, but multiple objects of available resources can be defined.

1.Semaphore

Semaphore maintains a set of license tokens, uses the acquire method to obtain the license token, and uses the release method to release a token. In fact, there is no real use license token, and semaphore only maintains available counters.

Semaphore is usually used to limit the number of access threads available to access some (physical or logical) resources. For example, the following class uses semaphore to control the amount of access to items in the pool.

Example:

When accessing items in the pool, each thread must obtain a license token from semaphore to ensure that one item is available. After the thread uses the item, it returns the item to the pool, and the access token is returned to semaphore.

Note: when the acquire method is called, a synchronization lock is not maintained, because the synchronization lock will prevent the item from being released to the pool. Semaphore encapsulates the required synchronization operations to ensure that the access to the pool is limited, rather than adding synchronization operations to maintain the consistency of the pool itself.

Semaphore is set to 1 by default to ensure that at least one license token is available. At this time, it can be regarded as a mutext exclusive lock. Mutex is famous as a binary semaphore, either with a license token or without a license token. When used in this way, binary semaphore is familiar (unlike most lock implementations), and the lock is released by the thread rather than the owner (semaphore has no concept of ownership). This is useful in some special scenarios, such as deadlock recovery.

The construction method of semaphore class can accept a fairness parameter. When this parameter is set to false, this class does not guarantee the order in which the thread obtains the license token, especially when running resource grabbing, which means that a thread may use acquire to obtain the license token earlier than a thread with a waiting queue before it -- logically, The new thread places the head of the monthly wait queue. When the fairness parameter is set to true, semaphore ensures that the thread obtains tokens in the order in which it calls the acquire method (i.e. first in first out FIFO)

reference:

【1】 http://www.cnblogs.com/think-in-java/p/5520462.html

【2】 http://blog.csdn.net/sunp823/article/details/49886051

【3】 http://coolxing.iteye.com/blog/1236909

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>