being interrupted while joining other threads
How should 开发者_JAVA百科I handle InterruptedException
while joining other threads, assuming I don't actually anticipate being interrupted, and there is no sensible thing to do? Just swallow the exception?
try
{
t.join();
u.join();
}
catch (InterruptedException e)
{
// should not happen
}
Or should I put each join
in its separate try/catch
, so if an InterruptedExeption
does happen while joining t
, at least u
gets a chance of being joined?
try
{
t.join();
}
catch (InterruptedException e)
{
// should not happen
}
try
{
u.join();
}
catch (InterruptedException e)
{
// should not happen
}
Or should I defensively swallow the exceptions in a loop, so I will eventually join both threads, even if some malicious guy tries to interrupt me?
while (true)
{
try
{
t.join();
break;
}
catch (InterruptedException e)
{
// no way, Jose!
}
}
while (true)
{
try
{
u.join();
break;
}
catch (InterruptedException e)
{
// no way, Jose!
}
}
On a side note, is there any case where InterruptedExeption
doesn't make my code look ugly? :)
If something shouldn't happen, you probably want to know if it ever does happen - and the best way of making it obvious is often to throw a RuntimeException
of some description (e.g. IllegalStateException
). If you're not anticipating the possibility of being interrupted, that suggests the system is in a state you're not really happy to support, so I wouldn't then try to keep going - aborting quickly is often the best option here.
You may want to write a helper method which does this for you, to make the calling code cleaner.
精彩评论