Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

Is there a mutex object in Java or a way to create one asking because a Semaphore object initialized with 1 permit does not help me. Think of this case:

try {

   semaphore.acquire();

   //do stuff

   semaphore.release();

} catch (Exception e) {

   semaphore.release();

}

If an exception happens at the first acquire, the release in the catch block will increase the permits, and the semaphore is no longer a binary semaphore.

Will the correct way be?

try {

   semaphore.acquire();

   //do stuff

} catch (Exception e) {

   //exception stuff

} finally {

   semaphore.release();

}

Will the code ensure that the semaphore will be binary?

1 Answer

0 votes
by (13.1k points)

You can do like this:

try {

  mutex.acquire();

  try {

    // do something

  } finally {

    mutex.release();

  }

} catch(InterruptedException ie) {

  // ...

}

Want to learn Java? Check out the Java certification and core Java certification from Intellipaat

In this case, you’re only calling release() after a successful acquire()

Related questions

0 votes
1 answer
asked Mar 4, 2021 in Java by Jake (7k points)
0 votes
1 answer

Browse Categories

...