Sergio AG Asked: 2020-06-09 16:40:52 +0800 CST 2020-06-09 16:40:52 +0800 CST 2020-06-09 16:40:52 +0800 CST Doubt of semaphores in Java 772 What is the difference in semaphores between using a .acquire()and a .tryAcquire()? Semaphore sem = new Semaphore(1); sem.acquire(); sem.tryAcquire(); java 1 Answers Voted Best Answer juandej18 2020-06-09T17:29:58+08:002020-06-09T17:29:58+08:00 According to the API the difference is the behavior of the methods: acquire: Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. tryAcquire: Acquires a permit from this semaphore, only if one is available at the time of invocation. The former blocks until the permit is available while the latter only acquires it if one is available at the time of invocation. Read the Javadoc for a better reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html
According to the API the difference is the behavior of the methods:
acquire:
Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted.
tryAcquire:
Acquires a permit from this semaphore, only if one is available at the time of invocation.
The former blocks until the permit is available while the latter only acquires it if one is available at the time of invocation.
Read the Javadoc for a better reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html