In Mutex.aquire why do we need to throw InterruptedException

P

puzzlecracker

It is a copy and paste from Doug Lea's Mutex implementation. I dont
understand the point of this line:
if (Thread.interrupted()) throw new InterruptedException();


public void acquire() throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
synchronized(this) {
try {
while (inuse_) wait();
inuse_ = true;
}
catch (InterruptedException ex) {
notify();
throw ex;
}
}
}


Thx
 
A

Arne Vajhøj

puzzlecracker said:
It is a copy and paste from Doug Lea's Mutex implementation. I dont
understand the point of this line:
if (Thread.interrupted()) throw new InterruptedException();

If interrupt has been called on the thread, then you do not
want to start waiting !?!?

Arne
 
A

Arne Vajhøj

Logan said:
Is that simply a performance optimization? If not, it looks like
there's a race condition, because the thread can get interrupted
after that 'if'-statement completes but before entering the
'synchronized' block.

Or to put it a different way, if the thread is interrupted, this
code doesn't seem to guarantee that you won't start waiting.

Correct.

But 99% early detect interrupt and 1% have wait throw
InterruptedException can still be considered an advantage.

I would assume Dough Lea to know what he is doing.

Arne
 
S

Szabolcs Ferenczi

Is that simply a performance optimization?  If not, it looks like
there's a race condition, because the thread can get interrupted
after that 'if'-statement completes but before entering the
'synchronized' block.

Or to put it a different way, if the thread is interrupted, this
code doesn't seem to guarantee that you won't start waiting.

I agree with you that it is an optimisation. However, since it is only
an optimisation, a race condition does not harm.

On the other hand, the check (Thread.interrupted()) is always added to
the call so it is also optimised for the interrupt rather than for the
normal case.

Best Regards,
Szabolcs
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top