[java] Is there a Mutex in Java?

Is there a Mutex object in java or a way to create one? I am 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 above code ensure that the semaphore will be binary?

The answer is


See this page: http://www.oracle.com/technetwork/articles/javase/index-140767.html

It has a slightly different pattern which is (I think) what you are looking for:

try {
  mutex.acquire();
  try {
    // do something
  } finally {
    mutex.release();
  }
} catch(InterruptedException ie) {
  // ...
}

In this usage, you're only calling release() after a successful acquire()


Each object's lock is little different from Mutex/Semaphore design. For example there is no way to correctly implement traversing linked nodes with releasing previous node's lock and capturing next one. But with mutex it is easy to implement:

Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire();  // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
//   throw InterruptedException now, so there is no need for
//   further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try { 
 found = x.equals(p.item); 
 if (!found) { 
   nextp = p.next; 
   if (nextp != null) { 
     try {      // Acquire next lock 
                //   while still holding current 
       nextp.lock.acquire(); 
     } 
     catch (InterruptedException ie) { 
      throw ie;    // Note that finally clause will 
                   //   execute before the throw 
     } 
   } 
 } 
}finally {     // release old lock regardless of outcome 
   p.lock.release();
} 

Currently, there is no such class in java.util.concurrent, but you can find Mutext implementation here Mutex.java. As for standard libraries, Semaphore provides all this functionality and much more.


Mistake in original post is acquire() call set inside the try loop. Here is a correct approach to use "binary" semaphore (Mutex):

semaphore.acquire();
try {
   //do stuff
} catch (Exception e) {
   //exception stuff
} finally {
   semaphore.release();
}

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


private final Lock _mutex = new ReentrantLock(true);

_mutex.lock();

// your protected code here

_mutex.unlock();

Any object in Java can be used as a lock using a synchronized block. This will also automatically take care of releasing the lock when an exception occurs.

Object someObject = ...;

synchronized (someObject) {
  ...
}

You can read more about this here: Intrinsic Locks and Synchronization


I think you should try with :

While Semaphore initialization :

Semaphore semaphore = new Semaphore(1, true);

And in your Runnable Implementation

try 
{
   semaphore.acquire(1);
   // do stuff

} 
catch (Exception e) 
{
// Logging
}
finally
{
   semaphore.release(1);
}

No one has clearly mentioned this, but this kind of pattern is usually not suited for semaphores. The reason is that any thread can release a semaphore, but you usually only want the owner thread that originally locked to be able to unlock. For this use case, in Java, we usually use ReentrantLocks, which can be created like this:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

private final Lock lock = new ReentrantLock(true);

And the usual design pattern of usage is:

  lock.lock();
  try {
      // do something
  } catch (Exception e) {
      // handle the exception
  } finally {
      lock.unlock();
  }

Here is an example in the java source code where you can see this pattern in action.

Reentrant locks have the added benefit of supporting fairness.

Use semaphores only if you need non-ownership-release semantics.


To ensure that a Semaphore is binary you just need to make sure you pass in the number of permits as 1 when creating the semaphore. The Javadocs have a bit more explanation.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to mutex

What is the Swift equivalent to Objective-C's "@synchronized"? Mutex lock threads When should one use a spinlock instead of mutex? Is there a Mutex in Java? Mutex example / tutorial? When should we use mutex and when should we use semaphore Proper use of mutexes in Python Lock, mutex, semaphore... what's the difference? Example for boost shared_mutex (multiple reads/one write)? What is mutex and semaphore in Java ? What is the main difference?

Examples related to semaphore

semaphore implementation "The semaphore timeout period has expired" error for USB connection Semaphore vs. Monitors - what's the difference? Is there a Mutex in Java? When should we use mutex and when should we use semaphore Lock, mutex, semaphore... what's the difference? Delete all SYSTEM V shared memory and semaphores on UNIX-like systems What is mutex and semaphore in Java ? What is the main difference? Difference between binary semaphore and mutex What is a semaphore?

Examples related to java.util.concurrent

WAITING at sun.misc.Unsafe.park(Native Method) Is there a Mutex in Java? Synchronization vs Lock

Examples related to concurrent-programming

Is there a Mutex in Java?