LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 15

Semaphore permits Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.concurrent.Semaphore;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Semaphore s = new Semaphore(3);
        s.acquire();
        s.acquire(2);
        boolean got = s.tryAcquire();          // no permits left: returns false immediately
        int avail = s.availablePermits();
        s.release(2);
        System.out.println(got + " " + avail + " " + s.availablePermits() + " " + s.tryAcquire());
    }
}
  • A false 0 2 true Correct
  • B true 0 2 true
  • C false 1 3 true
  • D false 0 2 false
Correct Answer: Option A

Three permits are taken, so tryAcquire fails; releasing two makes two available, and the final tryAcquire succeeds.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links