Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Interrupted exception chaining Date: Tue, 25 Sep 2012 08:56:13 -0400 Organization: A noiseless patient Spider Lines: 68 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 25 Sep 2012 12:56:20 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="ffb8f7085759b339c1002252b48331a4"; logging-data="9013"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19lUNE69fsAron092IRVh95" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20120907 Thunderbird/15.0.1 In-Reply-To: Cancel-Lock: sha1:azIvmBnGIttNqePjoJIOxPBJxLw= Xref: csiph.com comp.lang.java.programmer:18911 On 9/25/2012 6:25 AM, raphfrk@gmail.com wrote: > Is there a recommended way of "chaining" interrupted exceptions? > > This is to implement a method call that doesn't throw an interrupted exception, but which calls a method which can be interrupted. > > public void uninterruptableWait(Object c) { (Aside: This could probably be a `static' method.) > boolean done = false; > boolean interrupted = false; > synchronized (c) { > while (!done) { > try { > c.wait(); > done = true; > } catch (InterrupedException ie) { (Aside: `InterrupttttttttttttttttttttedException'.) > interrupted = true; > } > } > } > if (interrupted) { > Thread.currentThread().interrupt(); > } > } > > If that interrupt was unexpected, and causes a stack trace, then it would be nice if it could include the details from the thrown exception. > > Is there a better way to do the above? It seems you're trying to have things both ways: You "expect" the interrupt by catching it, but then want to consider it as "unexpected" anyhow. Also, you want to inform your caller but have chosen not to throw an informative exception. Since an exception is just an object, I suppose you *could* have the method return it, or return `null' if there was none: /** * Waits for notify() or notifyAll() on an object, in * spite of interruptions. * @param c The object to wait for. * @return {@code null} if no interrupts occurred while * waiting, or one of the {@code InterruptedException}s * if one or more were thrown. */ public static InterruptedException uninterruptableWait(Object c) { InterruptedException ex = null; for (;;) { try { c.wait(); return ex; } catch (InterruptedException ie) { ex = ie; } } } This looks vile to me, though. I think your difficulty is self-inflicted, and should be solved by rethinking your design. -- Eric Sosman esosman@ieee-dot-org.invalid