moorara
moorara

Reputation: 4226

A Mutex for inter-threading usages in Java?

I want a Mutex in Java which let me to wait on it in a thread and release it in another thread. I know that I can use a Semaphore with capacity of 1 but the problem is that the "acquire()" method throws "InterruptedException". Is there any special synchronization way for this purpose in Java?

Upvotes: 0

Views: 298

Answers (4)

jdevelop
jdevelop

Reputation: 12296

ThreadA

volatile boolean waitCondition = true

synchronized(lockObject) {
  while (waitContidion) {
    lockObject.wait();
  }
}

ThreadB

synchronized(lockObject) {
  waitCondition = false;
  lockObject.notifyAll();
}

or use Condition/Signal on Lock instances.

Correct handling of InterruptedException is very important, at least you must set it's interrupted flag with Thread.currentThread().interrupt() method in catch block.

Upvotes: 0

Enno Shioji
Enno Shioji

Reputation: 26882

Luckily, Semaphore provides this method for you :)

public void acquireUninterruptibly()

Acquires a permit from this semaphore, blocking until one is available. Acquires a permit, if one is available and returns immediately, reducing the number of available permits by one.

If no permit is available then the current thread becomes disabled for thread scheduling purposes and lies dormant until some other thread invokes the release() method for this semaphore and the current thread is next to be assigned a permit.

If the current thread is interrupted while waiting for a permit then it will continue to wait, but the time at which the thread is assigned a permit may change compared to the time it would have received the permit had no interruption occurred. When the thread does return from this method its interrupt status will be set.

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340743

InterruptedException is not an issue, just wrap it in a loop:

while(true) {
    try {
        semaphore.acquire();
        break;
    } catch(InterruptedException e) {
        //swallow, continue;
    }
}

However this code is not very safe and elegant, but will work providing that you "want to make sure you can acquire a permit!"

Upvotes: 1

pathfinder666
pathfinder666

Reputation: 189

if you have a code in which a thread is going to wait then you will definitely have to handle interrupted exception unless you are using synchronized block. Also, What is the problem with interrupted exception?

Upvotes: 0

Related Questions