Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx05.eternal-september.org!.POSTED!not-for-mail From: markspace Newsgroups: comp.lang.java.programmer Subject: Re: polling IRQs in a thread's code Date: Sun, 24 Mar 2013 21:54:14 -0700 Organization: A noiseless patient Spider Lines: 74 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Mon, 25 Mar 2013 04:52:13 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="fba3415ba68d85d643935af2f52f0b4b"; logging-data="4278"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18gDI2tzgJQfCrlq+Rs5/FAOuwrogOxcZw=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20130307 Thunderbird/17.0.4 In-Reply-To: Cancel-Lock: sha1:3C/y9wS+VlujvPvwiNphiY+Z7jA= Xref: csiph.com comp.lang.java.programmer:23111 On 3/24/2013 4:14 PM, markspace wrote: > > void run() > { > if( irq() ) { > cleanup(); > return; > } I posted this, and I didn't much like it when I posted, and now I'm pretty sure it's rubbish, as they say on the other side of the Atlantic. SwingWorker got me thinking about better ways to do this. void run() { try { // tons o' stuff } catch( InterruptedException ex ) { // clean up } } The trick now is to check for an interrupt often enough. If you're publishing data periodically with the SwingWorker#publish method, that might be a good place to check. However you might want to check more often as well. Either way, throwing an exception seems much easier and cleaner at the top level than manually breaking your code into discreet sections. If you have very complicated clean-up code, you might have to package the clean-up into discreet chunks so it can be executed by the top level clean-up code. class MyTask implements Runnable { // or SwingWorker private Runnable cleanup; public void run() { try { a(); b(); c(); } catch( InterruptedException ex ) { if( cleanup != null ) cleanup.run(); } } private void a() { cleanup = new CleanupA(); //... do stuff, then when done, reset cleanup cleanup = null; } private class CleanupA implements Runnable { public void run() { // vacuum and dust } } private void b() { // etc. } private void c() { // etc. } } That seems cleaner to look at, at least for what's written there. If you do use Runnable, don't overlook this simple transform to get a more modern version. Future future = new FutureTask( myTask, x );