Created
August 13, 2014 11:32
-
-
Save ruskotron/2ba7a23f3f29db9ab879 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Resource { | |
void monopolise() throws InterruptedException; | |
} | |
public class Interrupts implements Runnable { | |
private final MyResources myRes; | |
public Interrupts(MyResources myRes) { | |
this.myRes = myRes; | |
} | |
private void timeConsumingStuff() throws InterruptedException { | |
/* Allocate some resources */ | |
Resource res = myRes.getResource(); | |
try { | |
/* Perform some indeterminate-time operation on res */ | |
res.monopolise(); | |
/* Do some other bits and pieces */ | |
} finally { | |
myRes.cleanup(res); | |
} | |
} | |
public void run() { | |
try { | |
/* Use `isInterrupted` to idempotently interrogate interrupted status */ | |
while (!Thread.currentThread().isInterrupted()) { | |
timeConsumingStuff | |
} | |
} catch (InterruptedException consumed) { | |
/* Restore the interrupted status */ | |
Thread.currentThread().interrupt(); | |
} | |
} | |
public void cancel() { | |
interrupt(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment